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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by