How to build-up a column from top to bottom
1 view (last 30 days)
Show older comments
Hi everyone,
I want to build a function as shown below:
u=[];
for i =1:10
a = rand(1);
u = [a;u];
end
but the problem is that the first value is at the bottom of the column instead of at the top. i tried 'flipud' but i want it to build up normally (thus first value top, latest value bottom)
many thanks,
Paul
1 Comment
Stephen23
on 15 Jul 2015
This time I formatted your code for you, but next time your can do it yourself using the {} Code button that you will find above the textbox.
Answers (2)
Stephen23
on 15 Jul 2015
Edited: Stephen23
on 22 Jul 2015
The answer to your question is to swap a and u within the concatenation:
u = [u;a]
But this is poor MATLAB programming. Expanding arrays inside loops is a poor design choice because MATLAB has to keep checking and reallocating memory on every iteration. This is one of the main performance killers of beginners' code, and then they all complain "why is my code so slow?". Answer: because of looping and expanding arrays inside loops. Your entire code could be replaced by the much faster and more efficient:
u = rand(10,1)
And if you really do believe that you need to use a loop without using MATLAB's much more efficient code vectorization, then you should at least preallocate the array before the loop:
u = nan(10,1);
for k = 1:10
u(k) = rand(1);
end
This is neater and much more efficient than expanding the array in a loop.
0 Comments
See Also
Categories
Find more on Matrices and Arrays 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!