필터 지우기
필터 지우기

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에서 Introduction to Installation and Licensing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by