MATLAB Answers

0

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)

Asked by Jehanzeb Rana on 11 Nov 2018 at 1:18
Latest activity Edited by Stephen Cobeldick on 11 Nov 2018 at 7:43
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

What is count1 and count? Why do you intialize count1 twice but not count? Do you even need count at all?
Using linspace or colon would be much simpler and more efficient. And of course linspace avoids nasty floating point error accumulation.

Sign in to comment.

2 Answers

Answer by Star Strider
on 11 Nov 2018 at 1:23

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

  0 Comments

Sign in to comment.


Answer by Image Analyst
on 11 Nov 2018 at 1:29

Do you want to try it vectorized?
dt = 0.1
count1 = [0, cumsum(dt*ones(1,299))]

  0 Comments

Sign in to comment.