function [t,x] = euler(f, tRange, x0, n) % euler: Eulers 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 x(k+1) = x(k) + h*f(t(k),x(k)); end