Why am I am facing this error "Index in position 1 is invalid. Array indices must be positive integers or logical values."
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Jing Kai Wong
le 30 Avr 2022
Réponse apportée : Ahmad
le 30 Avr 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
Réponse acceptée
Walter Roberson
le 30 Avr 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 !
Plus de réponses (1)
Ahmad
le 30 Avr 2022
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 commentaires
Voir également
Catégories
En savoir plus sur Debugging and Analysis dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!