% Runge_Kutta_4_with_use_of_function    13.12.2023

% Script uses an internal function and will handle
% the ODE entered as the anonymous function "f".
% In addition, following  data has to be given:
%  x0 = Initial value of independent variable	
%  xf = Final value of independent variable
%  y0 = Initial solution value
%  h  = Step increment of independent variable

clear; close; clc
% Definition of some ODE functions using the same data
 % f = @(x,y) -20*y + 7*exp(-0.5*x);
   f = @(x,y) 3*x*y;

% Additional data:
x0 = 1; xf = 2; y0 = 1; y(1) = y0; h = 0.02;
                                 
% Calling the internal function RK4func
 [x,y] = RK4func(f, x0, xf, y0, h);

plot(x,y,'r-','LineWidth',0.5); xlabel('x'); ylabel('y')
title('Display of numerical obtained solution')
% ______________________________________________________

function [x,y] = RK4func(f, x0, xf, y0, h)	
                                         
 n = (xf-x0)/h;  % number of steps of independent variable
 x = x0:h:xf;    % vector of independent variable
 y(1) = y0;	     % initial solution value
    for i = 1 : n
    	k1 = h * f(x(i), y(i));
    	k2 = h * f(x(i)+h/2, y(i) + k1/2 );
	    k3 = h * f(x(i)+h/2, y(i) + k2/2 );
	    k4 = h * f(x(i)+h  , y(i) + k3   );
	    y(i+1) = y(i) + ( k1 + 2*k2 + 2*k3 + k4) / 6;
    end
end