simplest way to build a series of numbers inside a for loop

조회 수: 1 (최근 30일)
ddd ppp
ddd ppp 2018년 4월 21일
댓글: ddd ppp 2018년 4월 21일
im trying to build a series of numbers inside a for loop. here is what i used to do this.
t=0
dt=.1
ii=0
for i=1:10
% ii=[ii,i] %method one
t=[t,t(i)+dt] %method 2
end
is there a simpler method to do this?

채택된 답변

Ameer Hamza
Ameer Hamza 2018년 4월 21일

You can simply use vector notation available in MATLAB as follow:

t = 0:0.1:1
ii = 0:10   % or ii = 0:1:10, if 2nd number is 1, it can be emitted.

The use of vector notation is also recommended because it is efficient and readable.

  댓글 수: 3
Ameer Hamza
Ameer Hamza 2018년 4월 21일

So what do you mean by the simplest way? If you still want to use for loop then you can make improvement by pre-allocating the memory for the array as follow:

t=zeros(1, 11); %create 1x11 array of zeros
dt=.1;
ii=zeros(1, 11);
for i=1:10
  ii(i+1) = i;    %method one
  t(i+1)= t(i)+dt;  %method 2   
end

This pre-allocation will show significant improvement in speed if t is a very large vector. Other than vectorization, it cannot get any simpler than this.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by