% Solve Odes using Euler method % Einat function doall=euler clear all; close all; x(1)=1; %initial condition, x(t0) t(1)=0; %is taken at t0=0 tf=1; %final point x2(1)=x(1); xt(1)=x(1); xanalytical(1)=x(1); for d=0:4 dt=10^(-d); %time-step size N=tf/dt; %number of time steps %1st and 2nd order euler method for n=1:N x(n+1)=x(n)+dt*rhs(x,n); %1st order xt(n+1)=x2(n)+dt*rhs(x2,n); %trail of 2nd order x2(n+1)=x2(n)+0.5*dt*(rhs(x2,n)+rhs(xt,n+1)); %2nd order t(n+1)=t(n)+dt; xanalytical(n+1)=exp(-t(n+1)); end figure plot(t,x,'x-') hold on plot(t,x2,'ro-') plot(t,xanalytical,'g') title(dt) xlabel('t') ylabel('x(t)') legend('1st order','2nd order','analytical') end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % return f(n): function fn=rhs(x,n) fn=-x(n);