% MATH 3150 Fall 2008
% Demo for Fourier series approximation of sawtooth function
%  f(x) = (pi - x)/2 for 0<=x<=2*pi
x = linspace(-2*pi,4*pi,1000);

% plot true function for refernce
hold on;
% use mod(x,2*pi) instead of x to make 2*pi periodic function from a 
% function defined on [0,2*pi]
plot(x,0.5*(pi-mod(x,2*pi))); 
axis([-2*pi,4*pi,-2,2]); % 3 periods
pause; % wait for a key press event before continuing

% loop over number of terms
Ns = [1,2,5,10,15];
cols={'g','m','c','r','k'}; % using cell array to store colors
for iN = 1:length(Ns),
 N=Ns(iN);

 % compute partial Fourier series
 s=zeros(size(x));
 for n=1:N,
  s=s+(1/n)*sin(n*x);
 end;

 % comparative plot
 plot(x,s,cols{iN});
 pause; % stops program until user presses any key
end;%N
