MATLAB Answers

Runge Kutta 4th order

18 views (last 30 days)
Hello,
Here is the task that i have to solve:
y1' = y2
y2'=f(x,y1,y2) with y1(0)=0 and y2(0)=y20
where f(x,y1,y2) = -axy2-y1, a=0.03 and y20 = 0.25
and here is my matlab code:
--
function main
h = pi/10;
x = 0 : h : 2*pi;
n = length(x);
y(1,1)=0; y(2,1) = 0,25;
for k = 1: (n-1)
k1 = h * rung(x(k), y(1:2,k));
k2 = h * rung(x(k) + h/2, y(1:2,k) + k1/2);
k3 = h * rung(x(k) + h/2, y(1:2,k) + k2/2);
k4 = h * rung(x(k) + h, y(1:2,k) + k3);
y(1:2,k+1)=y(1:2,k) + (k1 + 2*k2 + 2*k3 + k4)/6;
end
figure(1), plot(x, y(2,:)) %everything from second row
figure(2), plot(x, y(1,:), x, ??, '*')
function f=rung(x,y)
f(1,1) = y(2);
f(2,1) = -0,03*x*y(2) y(1);
So, my question is - Is this correct or not? And what would be the best option for h and x.
And how can i found and use numerical solution? Because i know that instead of the question marks here figure(2), plot(x, y(1,:), x, ??, '*') should be the exact numerical solution.

Accepted Answer

Erivelton Gualter
Erivelton Gualter on 8 May 2019
Your code seems to have some issues. Try this one:
h = pi/10;
x = 0 : h : 2*pi;
n = length(x);
y = zeros(2,n);
y(:,1) = [0, 0.25];
for k = 1: (n-1)
k1 = h * rung(x(k), y(:,k));
k2 = h * rung(x(k)+h/2, y(:,k) + k1/2);
k3 = h * rung(x(k)+h/2, y(:,k) + k2/2);
k4 = h * rung(x(k)+h, y(:,k) + k3);
y(:,k+1) = y(:,k) + (k1 + 2*k2 + 2*k3 + k4)/6;
end
subplot(211); plot(x, y(1,:))
subplot(212); plot(x, y(2,:))
function f = rung(x,y)
f(1,1) = y(2);
f(2,1) = -0.03*x*y(2) - y(1);
end
  1 Comment
Melda Harlova
Melda Harlova on 9 May 2019
Thank you very much! It seems to be ok. But i did not understand why you usе this: y = zeros(2,n) and is this solution is numeric.
Thank a lot again. :)

Sign in to comment.

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!

Translated by