% Richard Duncan
% EE3133
% Assignment 4: Fourier Series 
% 2/13/97
%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Part II
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% - Construct a squarewave with a period of 1 msec and a duty cycle of 25%.
%   Assume the signal's phase is zero (meaning a period of the signal starts
%   a t=0).
%
clear all;
close;
dur = 20;
y=[];

for i = 1:dur
	tmp = [ones(1,25) zeros(1,75)];
	y = [y 	tmp];
end
y;

t = linspace(-0.01,0.01,100 * dur);
plot(t,y);
hold
% Now I'm going to use trigonometric fourier terms for this one, as it
% will be simpler to plot.
%
% Xn = 1/Cn int(x(t)* exp(-j*2*pi*n*f0*t,0,T))
%
% Xn = 1/Cn int(1 * exp(-j*2*pi*n*f0*t,0,T/4))+ 1/Cn * int(0,T/4,T)
% a(n) = 2/T * eval(int(x * cos(n*w0*t),t0,T+t0))
% b(n) = 2/T * eval(int(x * sin(n*w0*t),t0,T+t0))
%
% a(n) = 2/T * eval(int(1 * cos(n*w0*t),t0,T/4+t0)) + 0
% b(n) = 2/T * eval(int(1 * sin(n*w0*t),t0,T/4+t0)) + 0

num=50;

f0 = 1/0.001;
w0 = 2 * pi * f0;
Cn = 1/f0;
T = 1/f0;
syms t;
t0 = 0;

% determine the coefficients terms explicitely
%
for n=0:(num-1)
	 a(n+1) = 2/T * eval(int(1 * cos(n*w0*t),t0,T/4+t0));
	 b(n+1) = 2/T * eval(int(1 * sin(n*w0*t),t0,T/4+t0));
end


for n = 0:(num-1)
   at(n+1) = cos(n*w0*t);
   bt(n+1) = sin(n*w0*t);
end

% multiply the two vectors together, element by element
%
% Note: I first tried xt = a0 + a * transpose(at) + b * transpose(bt)
%       but it didn't work. The assumption is that that the mixed mode 
%       of symbolic/numeric data caused problems

xt = a(1);
for n = 2:num
   xt = xt + a(n) * at(n) + b(n) * bt(n);
end

t = linspace(-0.01,0.01,1000);

plot(t,eval(xt));

%   Using your Fourier series tool, plot the magnitude of Fourier series
%   coefficients as a function of frequency.
%
% Find the absolute value of each point from the origin
%
X = abs(a + j * b)

figure
freqs = linspace(f0,num*f0,num);
scatter(freqs,X,5,'b')		% combined terms
hold
scatter(freqs,abs(a),5,'g')	% imaginary terms
scatter(freqs,abs(b),5,'r')	% real terms

%   Explain the result.
%
% Obviously, fourier coefficients will decay exponentially as n increases.

% The reason that the plot goes to zero occasionally is the inherent

% symmetry in the square wave. The repeated pattern of 3 non-zero
% terms followed by a zero terms is a characteristic of the imaginary
% behaviour (the sin terms), as the real terms (cos) have all even terms
% dropping to zero. The pattern of 3-1 for the coefficients is also
% echo'd in the original waveform, 1 nonzero, 3 zero terms (25% duty
% cycle).

% end of file
%



