Why am I am facing this error "Index in position 1 is invalid. Array indices must be positive integers or logical values."
    5 ビュー (過去 30 日間)
  
       古いコメントを表示
    
I am trying to solve the 2 ODE using RK2 method and i require 2 iterations but when i try to solve for the 2nd iteration, it wont work but the first iteration is ok. 
clc
y1= @(t,y,z) -exp(-t).*y^2  %Write your f(x,t) function, where dy/dt=f(x,t)
y2 = @(t,y,z) y.^2 -0.1*exp(-t).*z
t0= 0; %initial value of t(0) 
y0= 1; %initial value of y(0)
z0 = 0;
h= 0.5; %step size
%Formula: k1=h*f(x0,y0);  k2=h*f(x0+h,y0+k1); y1=y0+(k1+k2)/2;     
for i=1:2
    k1=h*y1(t0,y0,z0);
    L1 = h*y2(t0,y0,z0);
    t1=t0+h; 
    k2=h*y1(t1,y0+k1,z0+L1);
    L2 = h*y2(t1,y0+k1,z0+L1);
    y1=y0+(k1+k2)/2;
    y2=z0+(L1+L2)/2;
    t0=t1;
    y0=y1;
    z0=y2;
end
y1 %ans
y2
t1
採用された回答
  Walter Roberson
      
      
 2022 年 4 月 30 日
        y1= @(t,y,z) -exp(-t).*y^2  %Write your f(x,t) function, where dy/dt=f(x,t)
y2 = @(t,y,z) y.^2 -0.1*exp(-t).*z
y1 and y2 are anonymous functions.
    y1=y0+(k1+k2)/2;
    y2=z0+(L1+L2)/2;
Not anymore they aren't! Now they are numeric variables !
その他の回答 (1 件)
  Ahmad
 2022 年 4 月 30 日
        Hi Wong 
You destroyed y1 and y2 functions in for loop;
mabe be this works 
clc
y1= @(t,y,z) -exp(-t).*y^2  %Write your f(x,t) function, where dy/dt=f(x,t)
y2 = @(t,y,z) y.^2 -0.1*exp(-t).*z
t0= 0; %initial value of t(0) 
y0= 1; %initial value of y(0)
z0 = 0;
h= 0.5; %step size
 %Formula: k1=h*f(x0,y0);  k2=h*f(x0+h,y0+k1); y1=y0+(k1+k2)/2;     
for i=1:2
    k1=h*y1(t0,y0,z0);
    L1 = h*y2(t0,y0,z0);
    t1=t0+h; 
    k2=h*y1(t1,y0+k1,z0+L1);
    L2 = h*y2(t1,y0+k1,z0+L1);
    y11=y0+(k1+k2)/2;
    y22=z0+(L1+L2)/2;
    t0=t1;
    y0=y11;
    z0=y22;
end
y11 %ans
y22
t1
0 件のコメント
参考
カテゴリ
				Help Center および File Exchange で Numerical Integration and Differential Equations についてさらに検索
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


