How to build-up a column from top to bottom

3 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2015-7-15
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.

请先登录,再进行评论。

回答(2 个)

Stephen23
Stephen23 2015-7-15
编辑:Stephen23 2015-7-22
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 2015-7-15
u=[]; for ii =1:10 a = rand(1); u = [u;a]; end

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by