How to build-up a column from top to bottom
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
Stephen23
am 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.
Antworten (2)
Stephen23
am 15 Jul. 2015
Bearbeitet: Stephen23
am 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 Kommentare
Siehe auch
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!