% Demonstration of Fourier transform from Fourier series, by increasing
% period
tmin = -10;  tmax = 10;
tv = tmin:0.001:tmax;

fh = figure;
for T=[2 3 4 5 6 7 8 16 32] 
  
  % Signal:  rectangular waveform, period T, pulse width 1
  x1v = mod(tv,T);
  xv = zeros(size(tv));
  xv(x1v<1/2) = 1;
  xv(x1v>T-1/2) = 1;
  subplot(3,1,1);  plot(tv,xv);
  axis([tmin tmax -0.25 1.25]);
  xlabel('time (s)');  ylabel('x_T(t)');
  title('From Fourier series to Fourier transform');
  
  % Coefficients
  w0 = 2*pi/T;
  wmin = -10;  wmax = 10;
  kmin = floor(wmin/w0);  kmax = ceil(wmax/w0);
  kv = kmin:kmax;
  wv = kv*w0;
  ckv = zeros(size(kv));
  for ki=1:length(kv)
    k = kv(ki);
    if k==0
      ckv(ki) = 1/T;
    else
      ckv(ki) = 1/(k*pi)*sin(k*pi/T);
    end
  end
  
  subplot(3,1,2);  sh = stem(wv,T*abs(ckv),'filled');
  set(sh,'MarkerSize',3);
  xlabel('\omega');  ylabel('T |c_k|');
  ax = axis;
  axis([wmin wmax ax(3) ax(4)]);
  subplot(3,1,3);  sh = stem(wv,angle(ckv),'filled');
  set(sh,'MarkerSize',3);
  ax = axis;
  axis([wmin wmax ax(3) ax(4)]);
  xlabel('\omega');  ylabel('\angle c_k');
  pause;
end