In: Mechanical Engineering
Write a user-defined MATLAB function that uses classical fourth order Runge-Kutta method to solve a first order ODE problem dydx = f(x, y) in a given interval a ? x ? b with initial condition y(a) = y0 and step size of h. For function name and arguments, use [x,y] = myrk4(f, a, b, h, y0)
Check your function to find the numerical solution for dydx=?1.2y+7e^(?0.3x) in the interval 0 ? x ? 4 with initial condition y(0)=3. Run your program three times for h=1.0, 0.1, 0.01 and plot all results along with analytical solution y=(70/9)*e^(?0.3x)?(43/9)*e^(?1.2x) on the same figure.
function [X,Y] = myrk4(f,a,b,h,y0)
syms x y
X = [a:h:b];
Y(1) = y0;
for i=1:size(X,2)-1
k1 = h*subs(f,{x,y},{X(i),Y(i)});
k2 = h*subs(f,{x,y},{X(i)+h/2,Y(i)+k1/2});
k3 = h*subs(f,{x,y},{X(i)+h/2,Y(i)+k2/2});
k4 = h*subs(f,{x,y},{X(i)+h,Y(i)+k3});
Y(i+1) = Y(i)+k1/6+k2/3+k3/3+k4/6;
end
clear
a = 0;
b = 4;
y0 = 3;
h = 1;
syms x y
f = -1.2*y+7*exp(-0.3*x);
Y_exact =@(x) (70/9).*exp(-0.3*x)-(43/9).*exp(-1.2*x);
figure('position',[0 0 800 300]);
hold on;
i=1;
for h=[1,0.1,0.01]
[X,Y] = myrk4(f,a,b,h,y0);
subplot(1,3,i)
plot(X,Y,X,Y_exact(X))
xlabel('X')
ylabel('Y')
title(['h=']+string(h))
legend('numerical','analytical')
i=i+1;
end