How i create a matrix from a nested loop?

3 ビュー (過去 30 日間)
DIMITRIOS THEODOROPOULOS
DIMITRIOS THEODOROPOULOS 2018 年 6 月 26 日
編集済み: Adam Danz 2018 年 6 月 26 日
For this simple loop
for i=1:5
for j=1:5
A=[i j]
end
end
the result i get is 25 arrays ,2x1 each one. But i want them gathered as a matrix of 25x2.How can i simply do it?
  1 件のコメント
Adam Danz
Adam Danz 2018 年 6 月 26 日
On each loop you're overwriting the value of A so you won't get 25 arrays, you'll get one array, 'A' that is of size [1-by-2] and A will equal [5,5] which are the last values of i and j.
You expect to get an array that is [25-by-2] but what values do you expect to be in that array?

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

採用された回答

Adam Danz
Adam Danz 2018 年 6 月 26 日
編集済み: Adam Danz 2018 年 6 月 26 日
If this is what you're looking for
A = zeros(5*5,2);
c = 0;
for i = 1:5
for j = 1:5
c=c+1;
A(c, :) = [i,j];
end
end
You can do this instead
A = [reshape(repmat(1:5,5,1),25,1), repmat(1:5,1,5)'];
  1 件のコメント
Stephen23
Stephen23 2018 年 6 月 26 日
Note that it is recommended to preallocate arrays before loops:
Array preallocation is a habit that all beginners need to learn.

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

その他の回答 (1 件)

Adam
Adam 2018 年 6 月 26 日
編集済み: Adam 2018 年 6 月 26 日
A = zeros( 25, 2 );
for i=1:5
for j=1:5
idx = 5 * ( i - 1 ) + j;
A(idx,:) =[i, j];
end
end
gives you what you want for your example, although there are much more efficient ways to create the resultant matrix than using a nested for loop, e.g.
A = [ repelem( 1:5, 5 ); repmat( 1:5, 1, 5 ) ]';
to throw in yet another variant!

カテゴリ

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