フィルターのクリア

How to save multiple outputs of a for loop and combining it into a matrix?

3 ビュー (過去 30 日間)
Jonathan Weaver
Jonathan Weaver 2017 年 12 月 5 日
編集済み: KL 2017 年 12 月 5 日
So I am trying to make a matrix using a for loop and right now I have it generating row vectors. But my questions is how do I assign the row vectors and combine them at the end. The way I have the code written is weird so I can't use vertcat.
if true
% III. Use For loop to generate the followig matrix "A":
% col1: 0 0 ... 0 (25 zeros)
% col2: 1 1 ... 1 (25 ones)
% col3: 2 2 ... 2 (25 twos)
% col4: 3 3 ... 3 (25 threes)
% col5: 4 4 ... 4 (25 fours)
% col6: 5 5 ... 5 (25 fives)
% col7: 6 6 ... 6 (25 sixes)
% col8: 7 7 ... 7 (25 sevens)
% col9: 8 8 ... 8 (25 eights)
% col10: 9 9 ... 9 (25 nines)
n=0
for i=1:10
a(1:1,1:25)=n
n=n+1;
end
end

採用された回答

KL
KL 2017 年 12 月 5 日
編集済み: KL 2017 年 12 月 5 日
It's always better to pre-allocate,
A = zeros(25,10); %number of rows, number of columns
Then use indexing,
for colNo = 1:size(A,2)
A(:,colNo) = ... %your value here
end
As you can see, you index one column during every iteration of the for loop, not 1:10. To index all rows, I've mentioned simply a colon (:). Please read the link I've mentioned above.
Just so you know, easier alternative is,
A = repmat(0:9,25,1);

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by