Order of iterations through a 5 dimensional nested for loop
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Alejandro Navarro
el 6 de Mayo de 2020
Comentada: Alejandro Navarro
el 6 de Mayo de 2020
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 comentario
Stephen23
el 6 de Mayo de 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;
Respuesta aceptada
Walter Roberson
el 6 de Mayo de 2020
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 comentarios
Walter Roberson
el 6 de Mayo de 2020
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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!