% A demonstration of building a square waveform using the Fourier Series
% expansion

% The Fourier series expansion for a square-wave is made up of a sum of odd
% harmonics. We can show this graphically using MATLAB. We start by forming a
% time vector running from 0 to 10 in steps of 0.1, then creating the
% fundamental frequency by taking the sine of all the points:

echo on
clc

t = 0:.1:10; y = (4/pi)*sin(t);

% Let's plot this fundamental frequency.

pause   % Strike any key for plot.

plot(t,y)
pause

% Now add the third harmonic to the fundamental, and plot it:

y = y + (4/pi)*sin(3*t)/3;

pause   % Strike any key for plot.

plot(t,y)
pause

% Now use the first, third, fifth, seventh, and ninth harmonics:

y = (4/pi)*(sin(t) + sin(3*t)/3 + sin(5*t)/5 + sin(7*t)/7 + sin(9*t)/9);

pause   % Strike any key for plot.

plot(t,y)
pause

% For a finale, we will go from the fundamental to the 27th harmonic, creating
% vectors of successively more harmonics, and saving all intermediate steps as
% rows in a matrix.

t = 0:.02:7;
y = zeros(10,max(size(t)));
x = zeros(1,max(size(t)));

for k=1:2:27
	x = x + (4/pi)*sin(k*t)/k;
	y(15-(k+1)/2,:) = x;
end      

% Let's plot these successively on an overplot, showing the transition to a
% square wave.  Note that Gibbs' effect says that it will never really get
% there.

pause   % Strike any key for plot.

for k=1:2:27; plot(t,y(15-(k+1)/2,:));
		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

