function [t,x] = rk2(f, tRange, x0, n) % rk2: 2nd order Runge-Kutta method for solving a single ODE % f: function f(t,x) defining x' % tRange: [t0,tEnd], the starting and ending times % x0: initial value of x % n: number of time steps so time values are t(1) to t(n+1) % [t,x]: an m by 2 matrix containing the (t,x) values % t and x are each column vectors. t0 = tRange(1); tEnd = tRange(2); h = (tEnd - t0) / n; t = (t0 : h : tEnd)'; % column vector x = zeros(length(t),1); x(1) = x0; for k = 1 : length(t)-1 k1 = h*f(t(k),x(k)); k2 = h*f(t(k+1),x(k)+k1); x(k+1) = x(k) + 0.5*(k1 + k2); end