Order of iterations through a 5 dimensional nested for loop
Ältere Kommentare anzeigen
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 Kommentar
Stephen23
am 6 Mai 2020
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;
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!