Hyper nested for loops
11 views (last 30 days)
Show older comments
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 Comments
Walter Roberson
on 17 Dec 2020
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 ?
Answers (2)
Walter Roberson
on 8 Dec 2020
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 Comments
Jan
on 17 Dec 2020
Edited: Jan
on 18 Dec 2020
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 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!