Is it possible to add row vectors into a matrix with a for loop?

26 ビュー (過去 30 日間)
Stewart Tan
Stewart Tan 2019 年 8 月 19 日
編集済み: Chris 2019 年 8 月 19 日
I wonder if it's possible to add rows of a matrix one at a time with a for loop? Example, if i initialize a blank matrix:
mat = [0 0 0];
and i have some dummy samples:
sample1 = [1 2 3];
sample2 = [4 5 6];
and i want to do something like:
for i=1:2
mat(i,:) = sample1;
end
so i would get:
mat = [1 2 3
4 5 6]
as the output. The idea is that what if i can't predefine the size of the matrix beforehand and that I'm not entirely sure how many sample will be there until the process ends? Is it possible in matlab?

採用された回答

Chris
Chris 2019 年 8 月 19 日
編集済み: Chris 2019 年 8 月 19 日
A loop is not needed for your simple demo
>> mat = [sample1; sample2]
mat =
1 2 3
4 5 6
But yes you can in general append to existing matrixies, it is best to preallocate when you can.
>> aa = [];
>> for ii = 1:5
aa(:,ii) = rand(3,1);
end
>> aa
aa =
0.90579 0.63236 0.54688 0.15761 0.48538
0.12699 0.09754 0.95751 0.97059 0.80028
0.91338 0.2785 0.96489 0.95717 0.14189
Note you have to define aa first. Also you need to append with consistent row/column lengths.
Edit: to prevent some future problems you might want to read:

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by