MATLAB code for R-K method
% From
https://www.mathworks.com/matlabcentral/fileexchange/29851-
runge-kutta-4th-order-ode?focused=3773771&tab=function
% It calculates ODE using Runge-Kutta 4th order method
% Author Ido Schwartz
% Modified by Irtaza Sohail
prompt1 = 'Type the value of starting point ''a''';
prompt2 = 'Type the value of ending point ''b''';
prompt3 = 'Type the step size ''h''';
prompt4 = 'Type the initial condition y(a)';
a = input(prompt1);
b = input(prompt2);
h = input(prompt3);
n=(b-a)/h; % step size
x = a:h:b;
y = zeros(1,n+1);
y(1) = input(prompt4); % initial condition
F_xy = @(t,y) y-t^2+1; % function
for i=1:n
k_1 = F_xy(x(i),y(i));
k_2 = F_xy(x(i)+0.5*h,y(i)+0.5*h*k_1);
k_3 = F_xy((x(i)+0.5*h),(y(i)+0.5*h*k_2));
k_4 = F_xy((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
y
Output (for example 3 page 289 9th edition)
Type the value of starting point 'a' 0
Type the value of ending point 'b' 2
Type the step size 'h' 0.2
Type the initial condition y(a) 0.5
y=
Columns 1 through 9
0.5000 0.8293 1.2141 1.6489 2.1272 2.6408 3.1799 3.7323 4.2834
Columns 10 through 11
4.8151 5.3054