# Using RK4 numerically rather than using an ODE solver

20 views (last 30 days)
KayLynn on 8 Feb 2014
Edited: darova on 26 May 2020
Use the 4th order Runge-Kutta (RK4) method with a step size of h = 0.1 and h=0.001 to find approximate values at t = 0.1, 0.2, …. to 5.0
I have the following code set up for this problem: function rungekutta
%Define initial values of h, t and y h = 0.1; t = 0; y = 1;
fprintf(Step 0: t = %12.8f, w = %12.8f\n’, t, w);
%Write for loop
for i=1:5
k1 = h*f(t,y);
k2 = h*f(t+h/2, y+k1/2);
k3 = h*f(t+h/2, y+k2/2);
k4 = h*f(t+h, y+k3);
y = y + (k1+2*k2+2*k3+k4)/6;
t = t + h;
fprintf(Step %d: t = %6.4f, w = %18.15f\n’, i, t, w); end
%%%%%%%%%%%%%%%%%%
function v = f(t,y)
v = y'= 2-e^-4*t-2*y;;
My t values range from 0 to 5 with step sizes of (0.1) and then another step size of (0.001). I am not sure how to fix the fprintf portion. Any help is appreciated.
Trying to follow the code found below on a website soruce: function rungekutta
h = 0.5;
t = 0;
w = 0.5;
fprintf(Step 0: t = %12.8f, w = %12.8f\n’, t, w);
for i=1:4
k1 = h*f(t,w);
k2 = h*f(t+h/2, w+k1/2);
k3 = h*f(t+h/2, w+k2/2);
k4 = h*f(t+h, w+k3);
w = w + (k1+2*k2+2*k3+k4)/6;
t = t + h;
fprintf(Step %d: t = %6.4f, w = %18.15f\n’, i, t, w); end %%%%%%%%%%%%%%%%%%
function v = f(t,y)
v = y-tˆ2+1;

Amit on 8 Feb 2014
f = @(t,y) (2 - exp(-4*t) - 2*y);
h = 0.1; % Define Step Size
t_final = 5;
t = 0:h:t_final;
y = zeros(1,numel(t));
y(1) = 1; % y0
% You know the value a t = 0, thats why you'll state with t = h i.e. i = 2
for i = 2:numel(t)
k1 = h*f(t(i-1),y(i-1));
k2 = h*f(t(i-1)+h/2, y(i-1)+k1/2);
k3 = h*f(t(i-1)+h/2, y(i-1)+k2/2);
k4 = h*f(t(i-1)+h, y(i-1)+k3);
y(i) = y(i-1) + (k1+2*k2+2*k3+k4)/6;
disp([t(i) y(i)]);
end
KayLynn on 8 Feb 2014
Thank you. I thought it was similiar but wasnt quite sure if the set up was generally the same since more variables have been added. You have been a great help today