MATLAB: How to create Runge-Kutta 4th order routine to solve first-order ODE’s

numerical integration

1. Write your own 4th order Runge-Kutta integration routine based on the general equations. Do not use Matlab functions, element-by-element operations, or matrix operations.

Best Answer

clear all
close all
clc
h = ___; % set the step size
x = ________; % set the interval of x
y = zeros(1,length(x));
y(__) = ___; % set the intial value for y
n = length(x)-1;
y_dot =@(x,y)(___________); %insert function to be solved
for i = 1:n
k1 = y_dot(x(i),y(i));
k2 = y_dot(x(i)+.5*h,y(i)+.5*k1*h);
k3 = y_dot(x(i)+.5*h,y(i)+.5*k2*h);
k4 = y_dot(x(i)+h,y(i)+k3*h);
y(i+1) = y(i)+((k1+2*k2+2*k3+k4)/6)*h;
end
[t,y_check] = ode45(y_dot,x,2);
plot(x,y)
title('Eulers Method')
figure
plot(x,y_check)
title('ode45 Check')