How to write a for loop with d indexes
1 view (last 30 days)
Show older comments
I am writing a for loop such like
for i_1 = 1:n_1
for i_2 = 1:n_2
...
for i_d = 1:n_d
end
end
end
How can I do this correctly? Thanks very much!
Accepted Answer
Jan
on 7 Apr 2022
Edited: Jan
on 7 Apr 2022
This is the code for 5 nested loops, but you set set d dynamically as you want:
nLoop = 5; % Number of loops, set as you want
n1=1; n2=2; n3=3; n4=4; n5=5;
ini = [1, 1, 1, 1, 1]; % Initial value
fin = [n1, n2, n3, n4, n5]; % Final value of each nested loop
nv = fin - ini + 1;
Output = cell([nv, 1]);
v = ini; % Start with initial values
for k = 1:prod(nv)
Output{k} = <your calculations here using index vector v>
% Update the index vector - this emulates nLoop nested loops:
for iv = 1:nLoop
if v(iv) < fin(iv)
v(iv) = v(iv) + 1;
break; % v(iv) increased successfully, leave "for iv" loop
end
v(iv) = ini(iv); % v(iv) reached the limit, reset it
end
end
More Answers (0)
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!