% integrate this ODE using Euler's method
% dx/dt = k*(1-x)
% clear old values from previous runs
% so xe and te arrays don't contain info from old run
clear
k = 1;
tmax = 6;
% this x vs. t is the analytical solution
t = [0:0.1:tmax];
x = 1-exp(-k*t);
% store t and x for Euler's method in arrays
% Matlab array indexes start at 1, not 0 as in C
ne = 1; % initial value of array index
te(ne) = 0;
xe(ne) = 0;
% dt is Euler's integration step size
% change this and see numerical error decreases
% as dt decreases however computation time also
% increases - there are more efficient methods
% (errors decrease faster with step size decrease)
% such as Runge-Kutta but Euler's gives you the main idea
dt = 1;
while te(ne) < tmax
dxdt = k*(1-xe(ne));
xe(ne+1) = xe(ne) + dxdt*dt;
te(ne+1) = te(ne) + dt;
ne = ne+1; % increment the array index
end
plot(t,x,'b',te,xe,'ko-')
title('dx/dt = k*(1-x) ; blue = analytical soln, black = Euler method')
xlabel('t')
ylabel('x')