function [x,t] = RK4(a,b,x0,N,f)
% Runge-Kutta method of 4th order to solve x' = f(t,x)
% INPUT:
%   - a and b       time interval [a,b] for which we will solve
%   - x0            initial condition; must be column vector
%   - N             number of points in discretization
%   - f             function handle f(t,x)
% OUTPUT
%   - x             solution for the ODE
%   - t             time discretized domain

dt = (b-a)/N; % time step
t = a:dt:b; % time domain
x = zeros(size(x0,1),N+1); % initialization of the solution
x(:,1) = x0; % initial condition

for ii = 1:N
    tt = t(ii);
    x0 = x(:,ii);
    k1 = f(tt,x0);
    k2 = f(tt + .5*dt,x0 + .5*dt*k1);
    k3 = f(tt + .5*dt,x0 + .5*dt*k2);
    k4 = f(tt,x0 + dt*k3);
    x(:,ii+1) = x0 + (1/6)*dt*(k1+2*(k2+k3)+k4);
end
end