merging column vectors from the loop in to a single matrix

9 ビュー (過去 30 日間)
Abex
Abex 2012 年 1 月 13 日
Every iteration my algorithm gives me a column vector and I want to form a new matrix composed of these column vectors together sequentially ( for example, the third column vector from the iteration will be the third column in the newly formed matrix). I will be thankful if anyone suggest me how to write a loop which can do so.
Abex

回答 (2 件)

Matt Tearle
Matt Tearle 2012 年 1 月 13 日
% preallocate space
x = zeros(m,n);
% iterate <=> loop over columns
for k = 1:n
y = ... % make vector here
x(:,k) = y; % store y as kth column of x
end
This is assuming you know how many iterations you will have. If not, you may suffer some performance degradation, but:
x = [];
while ...
y = ...
x = [x,y];
end

Michael
Michael 2012 年 1 月 13 日
Try something like:
matrix = zeros(rows, columns); % preallocate your matrix
for i = 1:columns
column = [your code here generates a 1 x rows matrix];
matrix(:,i) = column;
end
I think I got everything the right way around. The second line inside the loop saves the current column as the i^th column in the matrix. The first line should help for speed if you have many columns.

カテゴリ

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