Why do I receive "Index exceeds the number of array elements (1)" ?

1 view (last 30 days)
This function is giving me an "Index exceeds the number of array elements (1)" error, and I have looked through it for over an hour but I can't figure out where my error is. For some background, m and t are both defined already in my workplace and they are both vectors. I would appreciate any pointers so I can fix this error. Thank you!
function v = velocity(m,t)
ve = -2000;
g = 9.81;
cd = 0.1;
dt = t(2) - t(1);
tf = max(t);
tbar = 0.4*tf;
x = 0:dt:tbar;
m = length(x)+1;
n = length(t);
v=zeros(1, n);
for w = 2:m
v(w) = v(w-1) + dt*((100/m(w-1))*(v(w-1)-ve)-g-(cd/m(w-1))*abs(v(w-1))*v(w-1));
% v(i) = v(i-1)+dt*((v(i-1)-ve)*(100/(m(i-1)))-g-(cd/(m(i-1)))*abs(v(i-1))*(v(i-1)));
% v(i) = v(i-1) + dt*(-g-(cd/m(i-1))*abs(v(i-1))*v(i-1));
end
for w = m:n
v(w) = v(w-1) + dt*(-g-(cd/m(w-1))*abs(v(w-1))*v(w-1));
end
end

Accepted Answer

the cyclist
the cyclist on 15 Sep 2021
Edited: the cyclist on 15 Sep 2021
m is a scalar -- the length of the vector x, plus one.
You try to index into it as if it is a vector, for example in the expression
m(w-1)
So this fails with the error you see, when w==3.
  1 Comment
Mercedes Milke
Mercedes Milke on 15 Sep 2021
Thank you! That helped that error stop showing and I was actually able to run it now. I changed the name of the vector from m to another unrelated letter, and then I also changed it from the second for loop. I am now getting some very small values in comparison to what I need, but at least I have a point to go forward from. Thank you very much, again!

Sign in to comment.

More Answers (1)

Dave B
Dave B on 15 Sep 2021
You wrote:
For some background, m and t are both defined already in my workplace and they are both vectors.
But you redefined m as:
m = length(x)+1;
Doesn't that mean m is now a scalar? and when you point to m(w-1) it won't be valid?
  1 Comment
Mercedes Milke
Mercedes Milke on 15 Sep 2021
You're absolutely right. I needed to change the name of that so as to not redefine all my m values. Thank you for your response!

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!