MATLAB Answers

Solving ODEs using Runge Kutta Methods

3 views (last 30 days)
Abraham
Abraham on 18 Oct 2018
Answered: Meysam Mahooti on 5 May 2021
Total of 5 curves
So I'm to solve the above problem using 4 different methods and then display all 5 curves in the same graph. But it appears something is not right and I can't figure it out. I have attached my code to this message. After I ran the code, I got an error which I have been trying to fix, particularly the inline feature and I dont even know why the ode45 is also giving an error.
My code and the error below it
f=inline('y*t^2-1.5*y','t','y');
t0=0;
y0=1;
tf=2;
tspan = [t0 tf];
[t,y]=ode45(f,tspan,y0);
hold on
plot (t,y,'r')
clear t
h=0.5;
t(1)=t0;
euler5(1)=y0;
for i=1:4
t(i+1)=t(i)+h;
euler5(i+1)=euler5(i)+h*f(t(i),euler5(i));
end;
plot(t,euler5,'g')
clear t
h=0.25;
t(1)=t0;
euler25(1)=y0;
for i=1:8
t(i+1)=t(i)+h;
euler25(i+1)=euler25(i)+h*f(t(i),euler25(i));
end;
plot(t,euler25,'b')
clear t
h = 0.5;
midpoint(1) = y0;
t(1) = t0;
for i = 1 : 4
t(i+1) = t(i) + h;
z = midpoint(i) + h/2* f(t(i),midpoint(i));
midpoint(i+1) =midpoint(i) + h * f(t(i)+h/2,z);
end;
plot(t,midpoint,'y')
% Displays title information
h=0.5 ;
ta(1)=t0 ;
ya(1)=y0 ;
for i=1:4
% Adding Step Size
ta(i+1)=ta(i)+h ;
% Calculating k1, k2, k3, and k4
k1 = f(ta(i),ya(i)) ;
k2 = f(ta(i)+0.5*h,ya(i)+0.5*k1*h) ;
k3 = f(ta(i)+0.5*h,ya(i)+0.5*k2*h) ;
k4 = f(ta(i)+h,ya(i)+k3*h) ;
% Using 4th Order Runge-Kutta formula
ya(i+1)=ya(i)+1/6*(k1+2*k2+2*k3+k4)*h ;
end
plot(t,ya,'c')
legend('Exact','Eluer ,width 0.5','Euler width 0.25','Midpoint','RK fourth Order')
THIS IS THE Error I got.
Your knowledge and corrections are highly appreciated.

Accepted Answer

Torsten
Torsten on 18 Oct 2018
f = @(t,y)y(1)*t^2-1.5*y(1)
instead of
f=inline('y*t^2-1.5*y','t','y');

More Answers (1)

Meysam Mahooti
Meysam Mahooti on 5 May 2021
https://www.mathworks.com/matlabcentral/fileexchange/61130-runge-kutta-fehlberg-rkf78?s_tid=srchtitle

Community Treasure Hunt

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

Start Hunting!