function [ t, y ] = rk2 ( dydt, tspan, y0, n )

%*****************************************************************************80
%
%% rk2() solves an ODE with an explicit Runge-Kutta scheme of order  2.
%
%  Discussion:
%
%    This function uses an explicit Runge-Kutta method of order 2 to
%    approximate the solution of a differential equation of the form:
%      y' = dydt(t,y)
%      y(tspan(1)) = y0
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    10 November 2024
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    function handle dydt: defines the derivative function of the form
%      value = dydt ( t, y )
%
%    real tspan(2): contains the initial and final times.
%
%    real y0(m): contains the initial condition.
%
%    integer n: the number of steps to take.
%
%  Output:
%
%    real t(n+1): the times.
%
%    real y(n+1,m): the estimated solution values.
%
  m = length ( y0 );
  t = zeros ( n + 1, 1 );
  y = zeros ( n + 1, m );

  dt = ( tspan(2) - tspan(1) ) / n;

  t(1,1) = tspan(1);
  y(1,:) = y0(:);
 
  for i = 1 : n
    k1 = dt * dydt ( t(i),      y(i,:) );
    k2 = dt * dydt ( t(i) + dt, y(i,:) + transpose ( k1 ) );
    t(i+1,:) = t(i,:) + dt;
    y(i+1,:) = y(i,:) + 0.5 * transpose ( k1 ) + 0.5 * transpose ( k2 );
  end

  return
end

