## Welcome to the World of Modelling and Simulation

### What is Modelling?

This blog is all about system dynamics modelling and simulation applied in the engineering field, especially mechanical, electrical, and ... ### Fourth Order Runge Kutta Method by MATLAB to Solve System of Differential Equations

The fourth-order Runge-Kutta method (RK4) is a widely used numerical approach to solve the system of differential equations. In this module, we will solve a system of three ordinary differential equations by implementing the RK4 algorithm in MATLAB.

x' = -5x + 5y

y' = 14x - 2y - zx

z' = -3z + xy

The initial conditions are, x(0) = y(0) = z(0) = 1

The following MATLAB program implements RK4 scheme to solve the above system of three differential equations.

close all;

clc;
format long;

% Defining the three differential equations of the problem
f=@(t,y) [-5*y(1)+5*y(2), 14*y(1)-2*y(2)-y(1)*y(3), -3*y(3)+y(1)*y(2)];
[x,y]=runge_kutta_4(f,[0,5],[1,1,1],0.1); % Calling RK4 function defined below
plot(x,y);
title('When Time Step is 0.1');
legend('x(t)', 'y(t)', 'z(t)', 'Location', 'NorthEast')
xlabel('t')
ylabel('Solutions')
figure;
hold on;

for h=[0.1, 10^-3, 10^-6] % Implementing 3 different time steps
[x,y]=runge_kutta_4(f,[0,5],[1,1,1],h);
plot(x,y(:,1));
end

title('Plot of x(t) for 3 Different Time Steps');
legend('h=0.1', 'h=10^{-3}', 'h=10^{-6}');
xlabel('t')
ylabel('x(t)')

% Fourth order Runge-Kutta method
function [x,y]=runge_kutta_4(f,tspan,y0,h)
x = tspan(1):h:tspan(2); % Calculates upto y(3)
y = zeros(length(x),3);
y(1,:) = y0; % Initial Conditions
for i=1:(length(x)-1)
k_1 = f(x(i),y(i,:));
k_2 = f(x(i)+0.5*h,y(i,:)+0.5*h*k_1);
k_3 = f((x(i)+0.5*h),(y(i,:)+0.5*h*k_2));
k_4 = f((x(i)+h),(y(i,:)+k_3*h));
y(i+1,:) = y(i,:) + (1/6)*(k_1+2*k_2+2*k_3+k_4)*h;
end

end

Program Output:

1. Thank you, these codes are helpful.

1. 2. y'(t)=3e^-t -0.4y 0<t<2,y(0)=5
plz solved it

1. Hi there, you may use the codes shown in the post. In your case, it is more straightforward since you have one equation. You just need to define your equation in the following form:

% Defining the three differential equations of the problem
f=@(t,y) [-5*y(1)+5*y(2), 14*y(1)-2*y(2)-y(1)*y(3), -3*y(3)+y(1)*y(2)];

3. how can i use this code to solve ODEs of 5 variable

1. Hi Alok, you may apply the same method for 5 variables as well, you just need to arrange the equations in the same format shown in the post, and you have available initial conditions.

4. Thanks for sharing the code, but I got this result (Unrecognized function or variable 'runge_kutta_4'.
). Could you please tell what is wrong?

5. i need to solve with y(4) what can i do ?

6. 