Effacer les filtres
Effacer les filtres

How to write a for loop with d indexes

5 vues (au cours des 30 derniers jours)
Jingyu Liu
Jingyu Liu le 7 Avr 2022
Commenté : Stephen23 le 7 Avr 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!

Réponse acceptée

Jan
Jan le 7 Avr 2022
Modifié(e) : Jan le 7 Avr 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

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by