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

1 次查看(过去 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
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
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

类别

Help CenterFile Exchange 中查找有关 Debugging and Analysis 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by