echo on

% E_4_2.m
% This looks at effect of different length
% FFTs on spectral magnitude for cos(20*pi*t) 

% Sample at 100 Hz for 0.49 seconds -> 100 samples.
t = 0:0.01:0.5-0.01;

% Calculate x:  5 periods worth of data.
x = cos(20*pi*t);

% Do an N length FFT (effectively a DFT).
N = length(x);
X = fft(x,N);        

% Plot the spectrum
echo off
fp = (0:N-1)/N/0.01;
fp = fp - 1/2/0.01;
stem(fp,fftshift(abs(X)));
axis([ -1/(2*0.01) 1/(2*0.01) 0 25]); 
xlabel('freq. (Hz)')
ylabel('spectral mag')
echo on

% Note that there is ONE spectral component, at the frequency we expect.
pause              

X = fft(x,20*N);   % zero-padded DFT of 100 periods

% Plot
echo off
N = length(X);
fp = (0:N-1)/N/0.01;
fp = fp - 1/2/0.01;
plot(fp,abs(fftshift(X)));
axis([ -1/(2*0.01) 1/(2*0.01) 0 25]); 
xlabel('freq. (Hz)')
ylabel('spectral mag')
echo on

% Note that there is still one major frequency component; since we
% have extended the signal with zeros, there is some impreciseness
% about the data and so it is not as clear.

pause

% New data:  sample at 100 Hz for 0.44 seconds -> 45 samples
t = 0:0.01:0.5-0.01-1/20;

% Calculate x: 4.5 periods worth of data
x = cos(20*pi*t);

% Do a length N fft (effectively a DFT)
N = length(x);
X = fft(x,N);      

% Plot
echo off
fp = (0:N-1)/N/0.01;
fp = fp - 1/2/0.01;
plot(fp,abs(fftshift(X)));
axis([ -1/(2*0.01) 1/(2*0.01) 0 25]); 
xlabel('freq. (Hz)')
ylabel('spectral mag')
echo on

% Since we have taken 4.5 periods, the results aren't as clear as
% they are in the previous two examples.  The actual point we're 
% interested in is not a frequency calculated by the transform, so
% there is some of the result at the two nearest frequencies.

pause


