% Program for EE 329, Homework 3
% Using the FFT to plot the frequency spectrum of a rectangular pulse.
% Rich Kozick, February 1997

T = 0.01;	% Sample spacing
N = 100;	% Number of samples

Fs = 1/T;	% Sampling rate
f = (0:N-1)'/N*Fs;	% FFT frequencies in hertz
fa = linspace(0, Fs, 301); % Frequencies for plotting analog spectrum

% Generate sampled signal x and the sampling times

t = (T:T:0.1)';
x = ones(length(t), 1);
N1 = length(x);
if (N1 > N)
  fprintf('ERROR: Samples do not span the pulse duration\n');
  return;
end
N2 = N - N1;
t = [t; t(N1)+(T:T:(N2*T))'];
x = [x; zeros(N2,1)];

% Plot sampled time signal
figure(1)
plot(t, x, '-', t, x, 'o')
xlabel('t (sec)')
ylabel('x(t)')
s = sprintf('T = %f sec,   N = %d pts,   Fs = %f Hz', T, N, Fs);
title(s)

% Plot FFT
absX = abs(fft(x));
absX = absX/max(absX)*0.1;	% Normalize maximum amplitude to 0.1
figure(2)
plot(f, absX, ':', f, absX, 'x')
xlabel('f (Hz)')
ylabel('|X(k)|')
title('FFT MAGNITUDE')

% Plot analog signal spectrum
absXa = 0.1 * abs(sinc(fa/10));
figure(3)
plot(fa, absXa);
xlabel('f (Hz)')
ylabel('|Xa(f)|')
title('ANALOG SIGNAL MAGNITUDE SPECTRUM')

% Plot analog spectrum and FFT on same axes
figure(4)
plot(f, absX, ':', fa, absXa, '-');
legend('FFT', 'ANALOG FT')
xlabel('f (Hz)')
ylabel('Magnitude')
title('FFT AND ANALOG SIGNAL SPECTRUM')
