% A demonstration of building a composite waveform using the Fourier Series
% expansion
% 
% 
% The Fourier series expansion for a periodic wave is made up of a sum of even
% and odd harmonics. We can show this graphically using MATLAB. From class, we
% calculated the Fourier series coefficients as:
% 
% A0 = 3/4
% 
% An = -(sin((n*pi)/2)/(n*pi))
% 
% Bn = (1/(n*pi))*(cos((n*pi)/2) + 1 -2*(cos(n*p)))
% 
% We will go from the fundamental to the 16th harmonic, creating vectors of
% successively more harmonics, and saving all intermediate steps as rows in a
% matrix.
% 
pause   % Strike any key to continue

echo on
clc

t = 0:.02:3*pi;
y = zeros(16,length(t));
x = zeros(1,max(size(t)));
x = x + .75;

for n=1:16
	x = x - (sin((n*pi)/2)/(n*pi))*cos((n*pi*t)/4)  + (1/(n*pi))*(cos((n*pi)/2) + 1 -2*(cos(n*pi)))*sin((n*pi*t)/4);
	y(17-n,:) = x;
end                                     % Working, please wait.

pause   % Strike any key to continue

% Let's plot these successively on an overplot, showing the transition to our
% periodic wave.  Note that Gibbs' effect says that it will never really get
% there.
% 
pause % Strike any key for plot.

for k=1:16
	plot(t,y(17-k,:)), title('The building of a periodic wave')
	pause
end

% Now plot this as a 3-d mesh surface, showing, perhaps more vividly, the
% transition to a square wave.
% 
pause   % Strike any key for plot.

mesh(y)
pause
