merging column vectors from the loop in to a single matrix

8 Ansichten (letzte 30 Tage)
Abex
Abex am 13 Jan. 2012
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

Antworten (2)

Matt Tearle
Matt Tearle am 13 Jan. 2012
% 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 am 13 Jan. 2012
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.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by