how to increase the rows of an array in each loop?
Show older comments
Dear all, How to increase the elemnts of a multi dimentional array in each loop ? for example at first A=[], the next loop it will be A=[2 3 5 7] the third A= [ 2 3 5 7; 3 5 3 1 ] and so on. the colomn of A is attributes which is application-dependent.(I preferably want to use : to show all colomns)
Thanks
Answers (3)
Jan
on 25 Feb 2012
A = [];
for i = 1:5
A = cat(1, A, rand(1, 4));
% or:
% A = [A; rand(1, 4)];
end
But consider, that this is not efficient, because Matlab has to reserve the memory for the matrix in each iteration again and copy the former values. Look for "pre-allocation" in this forum to see better methods.
Dmitry Mittov
on 13 Mar 2015
sz = [5 4];
cell_A = arrayfun(@(i) rand(sz(2),1), 1:sz(1), 'UniformOutput', false);
A = cell2mat(cell_A)';
In my case I had vector X and wanted to get the matrix of [X; X .^ 2; X .^3; ... X .^ n]'. Not sure that works effective (in case of memory consumption), but looks so functional.
saharsahar
on 26 Feb 2012
4 Comments
saharsahar
on 26 Feb 2012
Image Analyst
on 26 Feb 2012
Seems like a strange thing to want to do. Sometimes A will be a 1D matrix, sometimes a 3D matrix, and sometimes a 42D matrix. Why don't you know how many dimensions your matrix will have in advance? What aren't you telling us? What does each dimension represent and why are there a variable number of them?
saharsahar
on 26 Feb 2012
saharsahar
on 26 Feb 2012
Categories
Find more on Loops and Conditional Statements 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!