# Why am I am facing this error "Index in position 1 is invalid. Array indices must be positive integers or logical values."

1 view (last 30 days)
Jing Kai Wong on 30 Apr 2022
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
Jing Kai Wong on 30 Apr 2022
Thanks all! I realised the mistake.

Walter Roberson on 30 Apr 2022
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 !
Jing Kai Wong on 30 Apr 2022
Thank you!

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