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
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 Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!