% MATLAB demonstration of a square wave filtered by a 1st-order lowpass filter
%
% ELEC 320, Rich Kozick, Fall 1998
%
% computes exponential Fourier series for Example 4.2
% used to generate Figures 4.6 - 4.9

t = -3:6/1000:3;
N = input('Number of harmonics ');
T = 1;		% Period
w0 = 2*pi/T;	% Fundamental frequency

c0 = 0.0;
xN = c0*ones(1,length(t));   % dc component

% Compute truncated exponential Fourier series

for n=1:N
  if (rem(n,2) == 0)	% Even harmonic
    cn = 0;
    c_n = 0;
  else			% Odd harmonic
    cn = 2 / (j*pi*n) * 1 / (1 + j*n*w0);
    c_n = 2 / (j*pi*(-n)) * 1 / (1 + j*(-n)*w0);
  end
  xN = xN + cn*exp(j*n*w0*t) + c_n*exp(-j*n*w0*t);
end

plot(t,xN)
title(['Filtered square wave with harmonics <= ',num2str(N)])
xlabel('Time (sec)')
ylabel(['x',num2str(N),'(t)'])

