merging column vectors from the loop in to a single matrix

13 visualizaciones (últimos 30 días)
Abex
Abex el 13 de En. de 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

Respuestas (2)

Matt Tearle
Matt Tearle el 13 de En. de 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 el 13 de En. de 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.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by