function Eulertest % This program uses Euler's method to solve the initial value problem % y' = y(1-y) for the initial value (0,0.1). In this example the % differential equation is solved for t between 0 and 5 % tstart = 0; % Start time tend = 5; % End time h = 0.1; % Delta t N = (tend-tstart)/h; % Number of steps tsol(1) = 0; ysol(1) = 0.1; % Apply the initial condition ysolI(1)= 0.1; %Eulers method: y_n+1 = y_n + f(t_n,y_n) h for i = 2:N+1 ysol(i) = ysol(i-1) + h * f(tsol(i-1),ysol(i-1)); tsol(i) = tsol(i-1) + h; end; %Eulers improed method (predictor-corrector): y_n+1 = y_n + f(t_n+ dt, y_n + h f(tn,xn)) dt for i = 2:N+1 yt = ysolI(i-1) + h * f(tsol(i-1),ysol(i-1)); fn = f (tsol(i-1) ,ysolI(i-1)); fn1 = f (tsol(i-1)+h, yt); ysolI(i) = ysolI(i-1) + h/2*(fn + fn1); tsol(i) = tsol(i-1) + h; end; yana = 1./(1 + 9*exp(-tsol)); E = abs(ysol-yana); EI = abs(ysolI-yana); figure(3); h=plot(tsol,ysol,tsol,ysolI,'g',tsol,yana,'r'); set(h,'linewidth',2); set(gca,'fontsize',20); xlabel('time'); ylabel('y'); xlim([0 5]); grid; figure(4); h=plot(tsol,E,'b',tsol,EI,'g'); set(h,'linewidth',2); set(gca,'fontsize',20); xlabel('time'); ylabel('error'); xlim([0 5]); grid; function dy = f(t,y) dy = y * (1-y);