%Script that demonstrates Euler integration for a first order problem using Matlab. % The problem to be solved is: %y'(t)=y-t^2+1 %Note: this problem has a known exact solution % y(t)= (t+1)^2 - 0.5exp(t) h=0.5; %h is the time step. t=0:h:2; %initialize time variable. t1=0:0.01:2; clear ystar; %wipe out old variable. ystar(1)=0.5; %initial condition (same for approximation). for i=1:length(t)-1, %Set up "for" loop. k1= ystar(i)-t(i)*t(i)+1.0; %Calculate derivative; ystar(i+1)=ystar(i)+h*k1; %Estimate new value of y; end %exact solution y= (t1+1).^2 - 0.5*exp(t1); %Plot approximate and exact solution. plot(t,ystar,'b--',t1,y,'r-',t,ystar,'o'); legend('Approximate','Exact'); title('Euler Approximation to dy/dt=y-t^2+1, h=0.5'); xlabel('Time'); ylabel('y*(t), y(t)'); %Print results for i=1:length(t) disp(sprintf('t=%5.3f, y(t)=%6.4f, y*(t)=%6.4f',t(i),y(i),ystar(i))); end