Info

This question is closed. Reopen it to edit or answer.

I want to store the values of count1 in the vector of zeros I have defined before the for loop. So the vector should be like [0 0.01 0.02 0.03 ..]. However, after the first iteration I get an error saying index exceeds the number of array element (1)

1 view (last 30 days)
count=0.0
dt=0.01
count1=zeros(1,300);
count1=zeros(1,300);
for n = 1:300
count1(n)=count(n)+dt(n);
end
  2 Comments
Stephen23
Stephen23 on 11 Nov 2018
Edited: Stephen23 on 11 Nov 2018
Using linspace or colon would be much simpler and more efficient. And of course linspace avoids nasty floating point error accumulation.

Answers (2)

Star Strider
Star Strider on 11 Nov 2018
The error refers to both ‘count’ and ‘dt’, that each have only one element, so you cannot subscript them beyond 1.
Try this:
count=0.0
dt=0.01
count1=zeros(1,300);
for n = 1:300
count1(n)=count+dt;
end

Image Analyst
Image Analyst on 11 Nov 2018
Do you want to try it vectorized?
dt = 0.1
count1 = [0, cumsum(dt*ones(1,299))]

Community Treasure Hunt

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

Start Hunting!