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 [tHist ,uHist] = ForwardEuler(f,tspan ,u0,nsteps)
T = [tspan(1) :nsteps: tspan(2)];
u = zeros(1,nsteps);
u(n) = u0;
h = (tspan(2) - tspan(1))/nsteps;
for i= 1: nsteps
u(i 1) = u(i) h*f(T(i),u(i));
tHist = [u(i 1)*T(i)];
uHist = [u(i 1)];
end
end
CodePudding user response:
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.