function [t,x] = rk4(f, tRange, x0, n) % rk4: 4th 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) + h/2, x(k) + k1/2); k3 = h*f(t(k) + h/2, x(k) + k2/2); k4 = h*f(t(k) + h, x(k) + k3); x(k+1) = x(k) + (k1 + 2*(k2 + k3) + k4) / 6.0; end