Another question on eliminating for loops....

2 ビュー (過去 30 日間)
Howard Wilton
Howard Wilton 2022 年 11 月 23 日
コメント済み: Howard Wilton 2022 年 11 月 23 日
I would like to eliminate for loops in the following code,
L=3; N=L; R=L^2 * N^2;
mat = int8(zeros(R,4));
ind = 1;
for n = 0:N-1
for p = 0:N-1
for l = 0:L-1
for q = 0:L-1
mat(ind,:) = [n,p,l,q];
ind = ind + 1;
end
end
end
end
Would welcome any insights.

採用された回答

John D'Errico
John D'Errico 2022 年 11 月 23 日
編集済み: John D'Errico 2022 年 11 月 23 日
Try it. If you can't see ndgrid doing it, then look harder. :) (By the way, lower case l (L) is a really bad variable name to use. DID I write a lower case L there, or was it the number 1, or perhaps an upper case I (i)?) Depending on the font, all of those characters/numbers can easily be confused. Your code will suffer from nasty bugs one day, due to typos, that you will never be able to find.
Anyway...
L=3; N=L;
[x,y,z,w] = ndgrid(0:N-1,0:N-1,0:L-1,0:L-1);
xyzw = [x(:),y(:),z(:),w(:)]
xyzw = 81×4
0 0 0 0 1 0 0 0 2 0 0 0 0 1 0 0 1 1 0 0 2 1 0 0 0 2 0 0 1 2 0 0 2 2 0 0 0 0 1 0
If you don't like the sequence generated by ndgrid with the first column moving fastest, then a sort will fix that.
xyzw = sortrows(xyzw,[1 2 3 4])
xyzw = 81×4
0 0 0 0 0 0 0 1 0 0 0 2 0 0 1 0 0 0 1 1 0 0 1 2 0 0 2 0 0 0 2 1 0 0 2 2 0 1 0 0

その他の回答 (1 件)

Steven Lord
Steven Lord 2022 年 11 月 23 日
Take a look at the ndgrid function.
  3 件のコメント
Torsten
Torsten 2022 年 11 月 23 日
編集済み: Torsten 2022 年 11 月 23 日
Ok, the order of the rows within the matrix has changed, but does it matter ?
Howard Wilton
Howard Wilton 2022 年 11 月 23 日
i didn't see it, but yes... sortrows and all is good.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by