How to write a for loop with d indexes

2 visualizaciones (últimos 30 días)
Jingyu Liu
Jingyu Liu el 7 de Abr. de 2022
Comentada: Stephen23 el 7 de Abr. de 2022
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!

Respuesta aceptada

Jan
Jan el 7 de Abr. de 2022
Editada: Jan el 7 de Abr. de 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

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by