Hyper nested for loops
조회 수: 11 (최근 30일)
이전 댓글 표시
Hi,
I want to create a series of nested "for loops" in order to calculate a constant faster:
my problem is that the function is iterative in such a way that it needs an addictional loop for every step of n:
I would like to build up something like this automatically, i give the code n and it does the rest:
say for example n = 3
it needs to create 3 nested for loops:
for p3 =1:5
for p2 = 1:5
for p1 = 1:5
do something
end
end
end
I'll give you another example, for n = 6 I wnat the code to build up like this:
for p6 = 1:5
for p5 =
.....
you get where this takes
...
end
end
how could I set up something like this? is it possible to do it or do I have to do it manually?
댓글 수: 6
Walter Roberson
2020년 12월 17일
Is sum(p_n) a constant? So that the values are "partitions" of a number ? Or are they all individually 0 to the positive number, so you effectively want to check all base-(that number) values with n (base-(that number)) digits ?
답변 (2개)
Walter Roberson
2020년 12월 8일
I give source code for this at https://www.mathworks.com/matlabcentral/answers/623358-get-a-combination-of-unique-paths-for-given-pair-of-numbers#comment_1082638 . The version there is generalized -- you can use an arbitrary number of entries per position, with arbitrary datatype, entries do not need to be consecutive (or numeric).
The code can be simplified a bit for simple numeric cases.
댓글 수: 0
Jan
2020년 12월 17일
편집: Jan
2020년 12월 18일
Instead of nesting loop, use one loop and a vector of indices:
n = 6; % n loops
m = 5; % Loops: for p_x = 1:m
p = ones(1, n); % Current index vector, starting at 1
Result = zeros(1, m^n); % Whatever matchs your output...
for k = 1:m^n
Result(k) = sum(p); % dummy for your "do something"
% Increase the index vector:
for ip = 1:n
if p(ip) < m
p(ip) = p(ip) + 1;
break; % Stop "for ip" loop
end
p(ip) = 1; % Reset this index
end
end
Alternatively create all possible combinations of p at once, if it fits into the memory:
n = 6;
m = 5;
c = cell(1, n);
c(:) = {1:m};
[d{1:n}] = ndgrid(c{:});
allp = reshape(cat(n+1, d{:}), [], n);
Now iterate through the rows of allp with one loop.
Note that the size of allp will grow rapidly and you can exhaust the memory easily. m=10 and n = 10 produces an allp of 80 GB. Using UINT8 values would reduce the size to 10 GB, but you see, that this approach is explosive.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!