merging column vectors from the loop in to a single matrix
6 views (last 30 days)
Show older comments
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
0 Comments
Answers (2)
Matt Tearle
on 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
0 Comments
Michael
on 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.
0 Comments
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!