% fsdemo.m - Fourier series demonstration for square wave in Problem
%            2.9-1(b) of Lathi text.
%
% R. Kozick, ELEC 470, Spring 2001

N = 1;       % Number of terms to include in Fourier series

w0 = 0.2;    % Fundamental frequency (rad/sec)
T0 = 10*pi;  % Period

dt = 3*T0/200;   % Spacing between time samples in g(t) approx.
t = -1.5*T0:dt:1.5*T0;
Nt = length(t);  % Number of samples in t

% Exact g(t) function:

z = find(((t>-11*pi)&(t<-9*pi)) | ((t>-pi)&(t<pi)) | ((t>9*pi)&(t<11*pi)));
gtrue = zeros(size(t));
gtrue(z) = ones(size(z));

% Use Fourier series with N terms to approximate g(t):

D0 = 0.2;
g = D0*ones(size(t));

for n=1:N
  D(n) = 1/(pi*n)*sin(n*pi/5);     % Note EVEN for +n and -n
  g = g + D(n)*exp(j*n*t/5) + D(n)*exp(-j*n*t/5);
end

figure(1)
subplot(211)
stem( (-N:N)*w0, [D(N:-1:1), D0, D(1:N)] );
xlabel('FREQUENCY (rad/sec)')
ylabel('D_n')
title('EXPONENTIAL FOURIER SPECTRUM')

subplot(212)
plot(t, g, 'r-', t, gtrue, 'b-')
legend('FOURIER SERIES APPROXIMATION', 'TRUE g(t)')
xlabel('t')
ylabel('g(t)')
s = sprintf('FOURIER SERIES WITH N = %d TERMS', N);
title(s)
axis([t(1) t(Nt) -1.5 1.5])
print -deps fsdemo1.eps

