%
%   NDEMO1.M   Solve y' = exp(-2x)-y with y(0) = 1  using Euler Method
%
%   This is the Matlab version of the class demo used to illustrate the basics
%   of the Euler method.  It calls the EULER function file to actually implement
%   the method.  The solution vector is plotted along with the exact solution
%   to demonstrate the improved accuracy obtained with smaller step sizes (increased N).
%
%   Some additional computations are also performed to extract intermediate results 
%   for comparison to hand calculations.
%
%   The function file EQN1.M containing the function definition is also required.
%
%   File prepared by J. R. White, UMass-Lowell (Feb. 2005)
%

%
%   getting started
      clear all;   close all;   nfig = 0;
%
%   define some initial parameters
      xo = 0;   xf = 0.5;  yo = 1; 
%
%   loop over different number of intervals (N)
      N = input('Input number of intervals, N, over the range [0 0.5] for EQN1: ');
%
      while N ~= 0
%   get numerical solution
        [x,y] = euler('eqn1',xo,xf,yo,N);
%   get function evaluation for comparison to hand calcs
        h = (xf-xo)/N;   k1 = h*feval('eqn1',x,y);
%   get exact solution for this problem (at same x values)
        ye = 2*exp(-x) - exp(-2*x);
%   compute max percent error 
        err = (y-ye)./ye;   errm = 100*max(abs(err));
%   echo numerical results to screen
        disp(' ')
        disp(['EULER Results for N = ',num2str(N)])
        disp('       i      x-value   y-euler     k1     y-exact   % error')
        icnt = 1:N+1;   [icnt' x y k1 ye err*100]
        disp(' ')
%   plot solution
        nfig = nfig+1;   figure(nfig)
        plot(x,y,'r.',x,ye,'g-','LineWidth',2),grid
        title(['Comparison of Solutions to y'' = exp(-2x) - y (N = ',num2str(N),')'])
        xlabel('x value'),ylabel('y-value')
        legend('Euler Method','Exact Soln')
        r = axis;   r(2) = xf;   axis(r);
        xt = r(1) + 0.05*(r(2)-r(1));   yt = r(3) + 0.05*(r(4)-r(3));
        text(xt,yt,['Max Error = ',num2str(errm),' %'])
%   try another N?
        N = input('Try a different N (enter zero to quit)? ');
      end
%
%   end of demo