フィルターのクリア

Order of iterations through a 5 dimensional nested for loop

2 ビュー (過去 30 日間)
Alejandro Navarro
Alejandro Navarro 2020 年 5 月 6 日
コメント済み: Alejandro Navarro 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; %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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by