Search code examples
matlabnumerical-methods

Euler method doesn't give correct output


I'm trying to write a MATLAB code for the Forward Euler method, but I don't think the output is completely correct.

This is my code:

function [t ,u] = Euler(f,tspan ,u0,n)

T = [tspan(1) :n: tspan(2)];
u = zeros(1,n);
u(n) = u0;
h = (tspan(2) - tspan(1))/n;
for i= 1: n 
    u(i+1) = u(i) + h*f(T(i),u(i));
    t = [u(i+1)*T(i)];
    u = [u(i+1)];
end
end

Solution

  • A minimal straightforward implementation could look like

    function [tHist ,uHist] = ForwardEuler(f,tspan ,u0,nsteps)
        tHist = linspace(tspan(1), tspan(2), nsteps+1);
        h = tHist(2)-tHist(1);
        uHist = zeros(nsteps+1,length(u0));
        uHist(1,:)=u0;
        for i = 1:nsteps
            uHist(i+1,:) = uHist(i,:) + h*f(tHist(i),uHist(i,:));
        end%for
    end%function
    

    Test the routine with the circle equation

    [T,U] = ForwardEuler(@(t,u)[u(2), -u(1)], [0,6.5], [1,0], 60);
    plot(U(:,1),U(:,2));
    

    which produces the expected outward spiral.