%
%   EIGENF2.M   Demo of Fourier Series Representation for f(x) = x(L-x)
%
%   The goal here is to evaluate the infinite series expansion for 
%   f(x) = x(L-x) in terms of sinusoids (i.e. a Fourier series expansion)
%
%   For this problem, the coefficients and basis functions are (see notes):
%      an = (8*L^2/pi^3)/m^3           gn(x) = sin(m*pi*x/L)          
%   with m = (2n-1)   and   n = 1, 2, ...
%
%   File prepared by J. R. White, UMass-Lowell (Aug. 2003)
%

%
%   getting started
      clear all, close all
%
%   set x domain and some constants
      L = 3;   Nx = 201;  x = linspace(0,L,Nx);   c = 8*L^2/pi^3;
%
%   calc exact function 
      fe = x.*(L - x);
%
%   calc Fourier Series approx
      fa = 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^3)*sin(m*pi*x/L);   fa = fa + ff;
        i = find(fa);                    % finds indices of nonzero values of fa
        mrerr = max(abs(ff(i)./fa(i)));  % compute max relative error
      end
%
%   plot curves
      plot(x,fe,'g-',x,fa,'r--','LineWidth',2),grid
      title('Eigen2:  Accuracy of Truncated Fourier Series for f(x) = x(L-x)')
      ylabel('f(x)'), xlabel('x value')
      legend('Exact f(x)','Approx f(x)')
      if n == Max,  gtext('not converged');  end
      if n < Max,   gtext([num2str(n),' terms for convergence']);  end
%
%   end of demo
