MATLAB: Does the example in FFT divide the FFT result by the length of the signal and multiply the magnitude of FFT by 2 when displaying the single side spectrum in MATLAB 7.8 (R2009a)

MATLAB

The documentation for FFT has the following example:
Fs = 1000; % Sampling frequency
T = 1/Fs; % Sample time
L = 1000; % Length of signal
t = (0:L-1)*T; % Time vector
% Sum of a 50 Hz sinusoid and a 120 Hz sinusoid
x = 0.7*sin(2*pi*50*t) + sin(2*pi*120*t);
y = x + 2*randn(size(t)); % Sinusoids plus noise
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
Y = fft(y,NFFT)/L;
f = Fs/2*linspace(0,1,NFFT/2+1);
% Plot single-sided amplitude spectrum.
plot(f,2*abs(Y(1:NFFT/2+1)))
title('Single-Sided Amplitude Spectrum of y(t)')
xlabel('Frequency (Hz)')
ylabel('|Y(f)|')
What are the motivations behind the following two lines:
Y = fft(y,NFFT)/L;
2*abs(Y(1:NFFT/2+1)) % in plot(f,2*abs(Y(1:NFFT/2+1)))

Best Answer

Since the calculated FFT will be symmetric such that the magnitude of only the first half points are unique (and the rest are symmetrically redundant), the main idea is to display only half of the FFT spectrum. The following code illustrates this point:
NumUniquePts = ceil((NFFT+1)/2);
FFTX=FFTX(1:NumUniquePts);
MX=abs(FFTX); % take magnitude of X
MX=MX*2; % multiply by 2 to take into account the fact that we threw out second half of FFTX above
However, the DC component of the signal is unique and should not be multiplied by 2:
MX(1)=MX(1)/2; % FFTX(1) is the DC component of x for both ODD and EVEN NFFT.
Also, for odd NFFT, the Nyquist frequency component is not evaluated, and the number of unique points is (NFFT+1)/2.
If NFFT is even, then the FFT will be symmetric such that the first (1+NFFT/2) points are unique, and FFTX(1+NFFT/2) is the Nyquist frequency component of x, which is unique. The rest are symmetrically redundant.
if ~rem(NFFT,2) % when NFFT is even, FFTX(1+NFFT/2) is the Nyquist frequency component of x, and needs to make sure it is unique.
MX(length(MX))=MX(length(MX))/2;
end
Try the following short example to see this:
a = [1 2 3 4 5]; A = fft(a) % 5-point FFT
b = [1 2 3 4 5 6]; B = fft(b) % 6-point FFT
You can see that A(1) (or B(1)) is the DC component of a (or b). Also, note that B(4) is the Nyquist frequency component of b (even NFFT), and A does not have such component. The divisions by 2 are done to take care of these unique components.
Related Question