MATLAB: Fft dosen’t conserve energy

digital signal processingMATLAB

I have an easy script, taken from an example of Matlab help page of fft:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear; close all; clc; beep off
Fs = 100; % Sampling frequency
t = -0.5:1/Fs:0.5; % Time vector
L = length(t); % Signal length
x = 1/(4*sqrt(2*pi*0.01))*(exp(-t.^2/(2*0.01))); % signal
nfft1 = 2^nextpow2(L); % first nfft
nfft2=nfft1/2; % new nfft (lower than first one)
dt=1/Fs; % time resolution
Y1 = fft(x,nfft1)*dt;
Y2 = fft(x,nfft2)*dt; % Fourier transforms
f1 = Fs*(0:(nfft1/2))/nfft1;
f2 = Fs*(0:(nfft2/2))/nfft2; % frequency arrays
P1 = Y1.*conj(Y1);
P2 = Y2.*conj(Y2); % power spectra
df1=f1(2)-f1(1);
df2=f2(2)-f2(1); % frequency resolutions
e=sum(abs(x).^2)/Fs % Energy from temporal domain
E1=sum(P1)*df1 % Energy from frequency domain with nfft1
E2=sum(P2)*df2 % Energy from frequency domain with nfft2
basically, I do the fft firstly with a nfft higher than the signal length (nfft1) and then with a lower nfft (nfft2); I get than the energy obtained with nfft1 is equal to the energy obtained from temporal domain, while energy obtained with a lower nfft is different. Could anyone explain why?

Best Answer

From the fft documentation:
Y = fft(X,n) returns the n-point DFT. If no value is specified, Y is the same size as X.
  • If X is a vector and the length of X is less than n, then X is padded with trailing zeros to length n.
  • If X is a vector and the length of X is greater than n, then X is truncated to length n.
The original ‘x’ has a length of 101. That is not compromised in the computation of ‘Y1’ becasue zero-padding simply increases the frequency resolution. The length of ‘x’ in ‘Y2’ is 64, so 37 elements of the original signal have been removed before the Fourier transform was calculated.
To illustrate:
Y1 = fft(x,nfft1)*dt;
Y2 = fft(x,nfft2)*dt; % Fourier transforms
Y3 = fft(x(1:64))*dt; % Truncate First
Y1Y2 = mean(abs(Y1)) - mean(abs(Y2))
Y2Y3 = mean(abs(Y2)) - mean(abs(Y3))
produces:
Y1Y2 =
-0.003722334257938
Y2Y3 =
0
There is no difference between ‘Y2’ and ‘Y3’. (The small difference between ‘Y1’ and ‘Y2’ is the effect of zero-padding in creating a longer ‘Y1’ vector without changing any of the other elements.)
Related Question