Error Message Index out of bounds

3 ビュー (過去 30 日間)
Kyle
Kyle 2014 年 2 月 11 日
編集済み: Image Analyst 2014 年 2 月 11 日
I have the code below and am getting the following error.
Attempted to access C(2); index out of bounds because numel(C)=1.
any ideas why?
h=0.1 ;
k1=0.005;
k2=0.005;
k3=0.1 ;
t=[0:h:200] ;
E(1)=10;
S(1)=100;
C(1)=0;
P(1)=0;
for i=1:numel(t)-1
%E
e1=(k2*C(i)+k3*C(i)-k1*E(i)*S(i));
e2=k2*[C(i)+(h*e1/2)]+k3*[C(i)+(h*e1/2)]-k1*[E(i)+(h*e1/2)]*[S(i)+(h*e1/2)]
e3=k2*[C(i)+(h*e2/2)]+k3*[C(i)+(h*e2/2)]-k1*[E(i)+(h*e2/2)]*[S(i)+(h*e2/2)]
e4= k2*[C(i)+(h*e3)]+k3*[C(i)+(h*e3)]-(k1*[E(i)+(h*e3)]*[S(i)+(e3*h)])
end
plot(t,e)
  1 件のコメント
Matt J
Matt J 2014 年 2 月 11 日
編集済み: Matt J 2014 年 2 月 11 日
In future, please highlight your code and apply the
formatting button, as I have just done for you now.

サインインしてコメントする。

回答 (2 件)

Matt J
Matt J 2014 年 2 月 11 日
any ideas why?
Yes. C is a scalar, but you are indexing it in your loop at many C(i) as if it were a vector. You must decide what C is really supposed to be.
  2 件のコメント
Kyle
Kyle 2014 年 2 月 11 日
i was just trying to indicate that the initial value for C is zero ( and the same for E S and P). is that not a valid way of going about it? do u have any suggestions on how to correctly code that?
Matt J
Matt J 2014 年 2 月 11 日
編集済み: Matt J 2014 年 2 月 11 日
But your loop doesn't refer only to the initial value of C, it refers to other C(i) too, which you have not supplied.

サインインしてコメントする。


Kyle
Kyle 2014 年 2 月 11 日
so the for loop actually had additional equations. ( i had thought, that if i isolated a set of the equations, i could figure out the concept of the code, w.o making it tedious . obviously that was incorrect.) the code is running now. but i keep getting "NaN" for a ton of my output. any idea why?
h=0.1 ; k1=0.005; k2=0.005; k3=0.1 ;
t=[0:h:200];
E(1)=10;
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+2*p3+p4)
end
plot(t,E)
hold on
plot(t,C)
plot(t,P)
plot(t,S)
  2 件のコメント
Matt J
Matt J 2014 年 2 月 11 日
Use
>>dbstop if naninf
to see where they are being introduced.
Image Analyst
Image Analyst 2014 年 2 月 11 日
編集済み: Image Analyst 2014 年 2 月 11 日
Your numbers are overflowing. Just look at some of them - they're huge. Eventually you reach infinity. What are you doing? Are you sure those are the right equations?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMathematics についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by