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

조회 수: 1 (최근 30일)
Mercedes Milke
Mercedes Milke 2021년 9월 15일
댓글: Mercedes Milke 2021년 9월 15일
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

채택된 답변

the cyclist
the cyclist 2021년 9월 15일
편집: the cyclist 2021년 9월 15일
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
Mercedes Milke
Mercedes Milke 2021년 9월 15일
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!

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

추가 답변 (1개)

Dave B
Dave B 2021년 9월 15일
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
Mercedes Milke
Mercedes Milke 2021년 9월 15일
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!

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by