In this video I'll explain and demonstrate how you can apply Euler's method to solve a differential equation (or a system of differential equations in matlab).
Code used:
%% Euler's method demonstration
% differential equation parameters
f = @(t,y) y; % solving dy/dt = y
y_init = 1; % with the initial condition y(0) = 1
Tspan = [0 5]; % for t = 0 to 5
for Tstep = [1, 0.1, 0.01, 0.001]
% apply euler method
[t, y] = euler(f, Tspan, y_init, Tstep);
% plotting
plot(t, y, linspace(Tspan(1), Tspan(end)), exp(linspace(Tspan(1), Tspan(end))));
legend('Euler method', 'Analytic solution'); grid minor; xlabel('t'), ylabel('y')
pause;
end
Code for the Euler's method function:
function [t, y] = euler(fun, Tspan, y_init, Tstep)
% initialize t vector
t = Tspan(1):Tstep:Tspan(end);
% pre allocate y vector
y = NaN(length(y_init),length(t));
y(:, 1) = y_init; % initial value for y is given
% euler method iterations
for k = 2:length(t)
y(k) = y(k-1) + Tstep*fun(t(k-1) ,y(k-1));
end