필터 지우기
필터 지우기

Order of iterations through a 5 dimensional nested for loop

조회 수: 2 (최근 30일)
Order = NaN([5 5 5 5 5]); %Creates a 5 dimensional matrix, where
% the length of each dimension is 5
n=1
for Loop5 = [1:5]
for Loop4 = [1 5];
for Loop3 = [1 5];
for Loop2 = [1:5];
for Loop1 = [1:5]
Order(Loop1,Loop2,Loop3,Loop4,Loop5) = n; %Line10
n = n + 1
end
end
end
end
end
To my understanding, this code should fill the "Order" matrix with sequential numbers from 1 through 3125, as line 10 should run 5^5 times total.
I expect loop 1 to be the first to iterate, through all 5 of it's steps,as below:
Order(1,1,1,1,1) = 1 ,
Order(2,1,1,1,1) = 2 ....
...and on to Order(3,1,1,1,1) = 5,
Then, Loop2 should tick forward one step, to 2, and again, loop 1 iterates 5 steps, while the loop2 variable stays at a value of 2 by this logic, Order(5,5,1,1,1) should be 25, and it is.
Up to here, everything works, but the third dimension, Order(1,1,2,1,1,)Never gets filled. Instead, number 26 ends up at Order(1,1,5,1,1).
How can I change the code so the 26th element to be filled is Order(1,1,2,1,1), and every element in the "Order" matrix has a value?
  댓글 수: 1
Stephen23
Stephen23 2020년 5월 6일
Getting rid of the superfluous square brackets makes the error very easy to spot:
for Loop5 = 1:5;
for Loop4 = 1 5; % <- missing colon
for Loop3 = 1 5; % <- missing colon
for Loop2 = 1:5;
for Loop1 = 1:5;

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2020년 5월 6일
Order = NaN([5 5 5 5 5]); %Creates a 5 dimensional matrix, where
% the length of each dimension is 5
n=1
for Loop5 = 1:5
for Loop4 = 1:5
for Loop3 = 1:5
for Loop2 = 1:5
for Loop1 = 1:5
Order(Loop1,Loop2,Loop3,Loop4,Loop5) = n;
n = n + 1;
end
end
end
end
end
  댓글 수: 3
Walter Roberson
Walter Roberson 2020년 5월 6일
Reread your code more carefully. You had
for Loop4 = [1 5];
That is the specific values 1 and 5, not all the values in the range 1 to 5.
Alejandro Navarro
Alejandro Navarro 2020년 5월 6일
lol whoops, totally missed that. thanks everyone!

댓글을 달려면 로그인하십시오.

추가 답변 (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