% File: E2_119.M
% This file demonstrates the Fourier Series representation of a
% 50% duty cycle square wave.

clear;

% Time is evaluated over the interval [0,10] in increments of t_inc.
% If you wish to observe Gibbs' phenomenon you should decrease the value
% of t_inc to 0.01, and include a large number of harmonics.
t_inc = 0.1;


% Enter the Number of Harmomics to include in the F.S.
fprintf('Enter the number of Harmonics to use in the Fourier Series, N.\n');
N = input('N should be an odd integer: ');
if (rem(N,2) == 0)
  N = N+1;
end;
fprintf('\n\nCalculating....please wait\n');

A = 1;
fo = 0.5;
wo = 2 * pi * fo;
t = 0:t_inc:10;
j = sqrt(-1);
for (n = 1:2:N)
  c(n) = A/(n*pi*j);
end;

i = 1;                                            
w = zeros(length(t),1);
while (i <= length(t))
  w(i) = A/2;
  for (n = 1:2:N)
    w(i) = w(i) + c(n)*exp(n*wo*t(i)*j) - c(n)*exp(n*wo*t(i)*(-j));
  end;
  i = i+1;
end;

plot(t,w);
title(['Fourier Series of Square Wave using ',int2str(N),' Harmonics']);
xlabel('time');
ylabel('w(t)');
  


                        



