Subscript Indices must either be real positive intergers or logicals - not sure where i'm going wrong.

1 回表示 (過去 30 日間)
I am trying to call the RK4 function below in order to find the second initial value for my main function. However it gets stuck at the y(2), which is meant to be the second initial value. RK4 is meant to use the Q2 function as its f in order to find this second value, then come back to the main function and input this as y(2). RK4 works absolutely fine and does not need changing, nor does Q2.
Could someone please help me understand why I am getting this error in the title when i try to use the second t and second y value in order to find the second initial y value? I need the y(2) value to be the second y value found in the RK4 file.
I'm doing my best to explain it but please ask if something needs more clarification.
Main Function:
function [t,y]= MainFunction(f,a,b,y0,m)
h=(b-a)/m;
y=zeros(1,m+1);
y(1)=y0;
t=a:h:b;
s=m;
y(2)=RK4(Q2(t(2),y(2)),h,y0,a,s);
y(3)=RK4(Q2(t(3),y(3)),h,y0,a,s);
for i=1:m-2
y(i+3)=y(i+2)+h/12*(23*f(t(i+2),y(i+2))-16*f(t(i+1),y(i+1))+5*f(t(i),y(i)));
end
end
RK4:
function [y,fvalues] = RK4(f,h,y0,a,s)
y=zeros(1,s+1);
fvalues=zeros(1,s+1);
y(1)=y0;
b = a+s*h;
t = a:h:b;
for i=1:s
fvalues(i) = f(t(i),y(i));
k1=h*fvalues(i);
k2=h*f(t(i)+h/2,y(i)+k1/2);
k3=h*f(t(i)+h/2,y(i)+k2/2);
k4 =h*f(t(i)+h,y(i)+k3);
y(i+1)=y(i)+ (1/6)*(k1+2*k2+2*k3+k4);
end
fvalues(s+1) = f(t(s+1),y(s+1));
end
Q2:
function Q=Q2(t,y)
Q=-(1+2.*t).*y;
This is the error as displayed in the command window:
>> MainFunction(@Q2,0,7,1,140)
Subscript indices must either be real positive integers or logicals.
Error in RK4 (line 10)
fvalues(i) = f(t(i),y(i));
Error in MainFunction (line 7)
y(2)=RK4(Q2(t(2),y(1)),h,y0,a,s);

採用された回答

Matt J
Matt J 2018 年 2 月 25 日
編集済み: Matt J 2018 年 2 月 25 日
Could someone please help me understand why I am getting this error
In
fvalues(i) = f(t(i),y(i));
you clearly intend f to be a function handle, but it is not. It is a numeric matrix and so the non-integers t(i) and y(i) are being viewed as an attempt to index that matrix.
  3 件のコメント
Matt J
Matt J 2018 年 2 月 25 日
I never said you should change RK4. Just pass an appropriate function handle for f, rather than a matrix.
Matthew Worker
Matthew Worker 2018 年 2 月 25 日
Oh right, sorry. Ok, I'll have a look at the help files to see if I can make sense of a function handle. Thank you!

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

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by