필터 지우기
필터 지우기

How to build-up a column from top to bottom

조회 수: 3 (최근 30일)
paul kaam
paul kaam 2015년 7월 15일
편집: Stephen23 2015년 7월 22일
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