function to code euler's method in matlab

Here's a MATLAB function that implements Euler's method to solve an initial value problem (IVP) for a first order ordinary differential equation (ODE):

main.m
function [t, y] = euler(f, y0, t0, tf, h)
% Implements Euler's method to solve the IVP:
%   y' = f(t, y), y(t0) = y0
% from t = t0 to t = tf with step size h.
% INPUTS:
%   f  - function handle for the RHS of the ODE y' = f(t, y)
%   y0 - initial condition
%   t0 - initial time
%   tf - final time
%   h  - step size
% OUTPUTS:
%   t - vector containing time steps
%   y - vector containing solution values at each time step

t = t0:h:tf;       % vector of time steps
y = zeros(size(t)); % vector of solution values
y(1) = y0;          % initial condition

for i = 1:length(t)-1
    y(i+1) = y(i) + h*f(t(i), y(i)); % Euler's method
end

end
643 chars
24 lines

You can use this function by passing in the function f defining the ODE, the initial condition y0, the initial time t0, the final time tf, and the step size h. For example, let's use Euler's method to solve the IVP y' = -y, y(0) = 1 from t = 0 to t = 5 with step size h = 0.1:

main.m
f = @(t, y) -y; % RHS of y' = -y
y0 = 1;         % initial condition
t0 = 0;         % initial time
tf = 5;         % final time
h = 0.1;        % step size

[t, y] = euler(f, y0, t0, tf, h); % solve the IVP

plot(t, y) % plot the solution
xlabel('t')
ylabel('y')
title("Euler's method with h = " + h)
302 chars
13 lines

This will produce a plot of the solution:

Euler's method solution plot

related categories

gistlibby LogSnag