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.

请先登录,再进行评论。

更多回答(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