euler forward method in matlab in matlab

main.m
function [t, y] = eulerForward(f, tspan, y0, h)
    % f is the function dy/dt = f(t, y)
    % tspan is the interval [t0, tf]
    % y0 is the initial value of y
    % h is the step size
    t0 = tspan(1);
    tf = tspan(2);
    
    t = t0:h:tf;  % create a time vector with step size h
    y = zeros(size(t));  % initialize the solution vector
    
    y(1) = y0;  % set the initial condition
    
    for i = 1:(length(t) - 1)
        y(i+1) = y(i) + h * f(t(i), y(i));
    end
end
483 chars
18 lines

To use the eulerForward function, define your differential equation f, the time span tspan, initial value y0, and step size h. Call the function with these inputs, and it will return the time vector t and the corresponding solution vector y using the Euler Forward method.

related categories

gistlibby LogSnag