Why do I receive "Index exceeds the number of array elements (1)" ?
1 view (last 30 days)
Show older comments
Mercedes Milke
on 15 Sep 2021
Commented: Mercedes Milke
on 15 Sep 2021
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
0 Comments
Accepted Answer
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.
More Answers (1)
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?
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!