Runge Kutta for system of eqs

6 views (last 30 days)
jojo
jojo on 24 Nov 2019
Edited: jojo on 26 Nov 2019
I would like to approxiamte and plot the following system of equations: { u' = v ; v' = -4*u' - 5 u} using the Runge Kutta method.
I am able to plot it for the second equation, but having difficulties incorporating the u' = v to reflect the full system.
the exact solution I am comparing to is: x(t) = 3.*exp(-2.*t) .* cos(t) + exp(-2.*t) .* sin(t) corresponding to equation: ??′′(??)+4??′(??)+5??(??)=0 with ??(0)=3 and ??′(0)=−5. as initial conditions.
clear all
close all
clc
h = .1; % set the step size
x = 0:h:5; % set the interval of x
y = zeros(1,length(x));
y(1) = 3; % set the intial value for y
n = length(x)-1;
y_dot =@(x,y)(-4*x-5*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
Please explain the any updates yu make, since I am new to ML and need to conceptually understand the fundamentals.
Thanks.
  3 Comments
jojo
jojo on 25 Nov 2019
Yes. ?′′(?)+4?′(?)+5?(?)=0 this is the full equation.
jojo
jojo on 25 Nov 2019
Edited: jojo on 25 Nov 2019
Just having difficulty breaking it into a system of equations and incorporate it into the code

Sign in to comment.

Answers (1)

darova
darova on 25 Nov 2019
I wrote function in the way similar to ode45
y_dot = @(x,dx)[dx; -4*dx-5*x]; %insert function to be solved
for i = 1:n
k1 = y_dot(x(i),dx(i));
k2 = y_dot(x(i)+h/2*k1(1), dx(i)+h/2*k1(2));
k3 = y_dot(x(i)+h/2*k2(1), dx(i)+h/2*k2(2));
k4 = y_dot(x(i)+k3(1), dx(i)+k3(2));
u = (k1+2*k2+2*k3+k4)*h/6;
% shorter form
% k1 = h/2*y_dot(x(i),dx(i));
% k2 = h/2*y_dot(x(i)+k1(1), dx(i)+k1(2));
% k3 = h* y_dot(x(i)+k2(1), dx(i)+k2(2));
% k4 = h* y_dot(x(i)+k3(1), dx(i)+k3(2));
% u = (2*k1+4*k2+2*k3+k4)/6;
x(i+1) = x(i) + u(1);
dx(i+1) = dx(i) + u(2);
end

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!