%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                 Math 750  -  Fall 2006                 %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% R.C. Sharpley
%%%%%%%%%%%%%%%
% Demonstration of convergence behavior of the 
% N-th Fourier Partial Sums and the Cesaro Means
% =======================================================
%
% This demo illustrates the rate at which the characteristic 
% funtion of (-pi/2,pi/2)may be approximated by its N-th
% Fourier partial sums 
%     S_N(t) = 1/(2*pi) + sum_{k=1}^N 2*sin(k/2)/(k*pi)*cos(k*t)
% as well as other effects and artifacts.

clear all,
clf; hold off
%%%%%%%%%%%%%%%%%%%%%
% Set m for the number of trig terms in the sum

m= 100

%%%%%%%%%%%%%%%%%%%%%
%  Build the t-grid for computing and plotting.

t = -pi:.001:pi; n=length(t);

%%%%%%%%%%%%%%%%%%%%%
% Build the target characteristic function for plotting

Chi = zeros(1,n);
for j=1:n;
   if abs(t(j))<.5,
      Chi(j)=1;
      end
   end;

%%%%%%%%%%%%%%%%%%%%%
% Build the partial sums, row-by-row, where the j-th column corresponds
% to the value at the grid point t(j). Start with constant first term

S(1,:)=1/(2*pi)*ones(size(t));  

%%%%%%%%%%%%%%%%%%%%%
% Simultaneously compute the Cesaro means row-by-row

Ces(1,:)=S(1,:);


%%%%%%%%%%%%%%%%%%%%%
% Now interatively compute the next term in each of the series

for k=1:m;
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % k-th Fourier harmonic   %%

    S(k+1,:)=S(k,:)+2*sin(k/2)/(k*pi)*cos(k*t);

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % weight to compute Cesaro update   %%

    lambda=1/(k+1);
    Ces(k+1,:) = lambda * S(k+1,:) + (1-lambda) * Ces(k,:);

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % Plotting to observe relative behavior   %%

    hold off
    plot(t,Chi,'r',t,Ces(k+1,:),'b',t,S(k+1,:),'g',t,zeros(size(t)),'k');
    axis manual; axis([-pi,pi,-.1,1.1]);
    text(-2.5,.9,['n =',num2str(k)],'fontsize',12,'fontweight','bold')
    hold on
    pause(.2)
  end;					

