function [y,t] = forwardEuler(y0,tfinal,nsteps) % function [y,t] = forwardEuler(y0,tfinal,nsteps) % % Forward Euler for nonlinear equations % % This function uses Forward Euler to solve % y' = f(t,y) % y(0) = y_0 % That is, for n = 1,2,3, ... % y_{n+1} = y_n + (t_{n+1} - t_n)f(t_n,y_n) % % We assume that an m-file function f.m exists for computing f: [ff] = f(t,y). % % Inputs: % y0 The initial condition (either a row or column vector). % tfinal The final time. % nsteps The number of steps to take. % Outputs: % y The solution. % Internal Variables: % dt The time step. % n The time step number. % t The current time. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Checking of inputs % if tfinal <= 0 y = y0; return; end if nsteps <= 0 nsteps = 1; end % % Initialization % dt = tfinal/nsteps; y(1) = y0; t(1) = 0; % % Time step loop % for n = 1:nsteps y(n+1) = y(n) + dt*f(t(n),y(n)); t(n+1) = t(n) + dt; end return;