%
%   EIGENF3.M   Demo for using Fourier Series for solving BVPs
%
%   The goal here is to use Fourier Series to solve the simple BVP given by
%        y'' + 4y = 1   with   y(0) = 0   and   y(L) = 0
%   and to compare the approximate series solution with the exact solution (see
%   Case 1 in Example 9.2 in the Math Method Notes for details).
%
%   File prepared by J. R. White, UMass-Lowell (Aug. 2003)
%

%
%   getting started
      clear all, close all
%
%   set x domain 
      L = 3;   Nx = 201;  x = linspace(0,L,Nx);   
%
%   calc exact solution 
      ce = (cos(2*L)-1)/(4*sin(2*L));
      ye = -(1/4)*cos(2*x) + ce*sin(2*x) + 1/4;
%
%   calc Fourier Series approx to y(x)
      c = 4/pi;   ya = zeros(size(x));
      Max = 100;   tol = 0.001;   mrerr = 1.0;   n = 0;
      while mrerr > tol   &    n < Max
        n = n+1;  m = 2*n-1;   
        ff = (c/m)/(4-(m*pi/L)^2)*sin(m*pi*x/L);   ya = ya + ff;
        i = find(ya);                    % finds indices of nonzero values of fa
        mrerr = max(abs(ff(i)./ya(i)));  % compute max relative error
      end
%
%   plot curves
      plot(x,ye,'g-',x,ya,'r--','LineWidth',2),grid
      title('Eigen3:  Accuracy of Fourier Series for the Case 1 BVP from Ex. 9.2')
      ylabel('y_1(x)'), xlabel('x value')
      legend('Exact y_1(x)','Approx y_1(x)')
      if n == Max,  gtext('not converged');  end
      if n < Max,   gtext([num2str(n),' terms for convergence']);  end
%
%   end of demo
