Azzera filtri
Azzera filtri

How to build-up a column from top to bottom

3 visualizzazioni (ultimi 30 giorni)
paul kaam
paul kaam il 15 Lug 2015
Modificato: Stephen23 il 22 Lug 2015
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 Commento
Stephen23
Stephen23 il 15 Lug 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.

Accedi per commentare.

Risposte (2)

Stephen23
Stephen23 il 15 Lug 2015
Modificato: Stephen23 il 22 Lug 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.

Andrei Bobrov
Andrei Bobrov il 15 Lug 2015
u=[]; for ii =1:10 a = rand(1); u = [u;a]; end

Community Treasure Hunt

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

Start Hunting!

Translated by