How to write a for loop with d indexes

4 次查看(过去 30 天)
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!

采纳的回答

Jan
Jan 2022-4-7
编辑:Jan 2022-4-7
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by