make a function that solves odes by forward euler in matlab

main.m
function [t, y] = forwardEuler(f, y0, t0, tf, dt)
% This function solves ODEs using forward Euler's method in matlab
% Inputs:
%   - f: function handle of the ODE, e.g. @(t, y) 3 * t - 10 * y
%   - y0: initial state of the system
%   - t0: initial time
%   - tf: final time
%   - dt: time step size
% Outputs:
%   - t: time vector
%   - y: state vector

% Initialize vectors
t = t0:dt:tf;
y = zeros(size(t));
y(1) = y0;

% Apply forward Euler method
for i = 1:length(t)-1
    y(i+1) = y(i) + dt * f(t(i), y(i));
end

end
521 chars
24 lines

You can call this function and pass in the appropriate inputs. For example:

main.m
f = @(t, y) 3 * t - 10 * y;
y0 = 0;
t0 = 0;
tf = 10;
dt = 0.1;
[t, y] = forwardEuler(f, y0, t0, tf, dt);
105 chars
7 lines

This will give you the time vector t and state vector y for the ODE dy/dt = 3t - 10y with initial condition y(0) = 0 and time range t=0 to t=10 with a time step size of dt = 0.1.

gistlibby LogSnag