MATLAB: How to use ‘fft’ to calculate the PSD of a signal that is padded with zeros

dftfftMATLABpadpointspsdSignal Processing Toolbox

I'm trying to compute a power spectral density (PSD) using the 'fft' function and I would like to specify the number of DFT points so that the signal is padded with zeros. There are instructions on how to find the PSD here: https://www.mathworks.com/help/signal/ug/power-spectral-density-estimates-using-fft.html, but I'm not sure how to modify them to allow me to pad the signal.

Best Answer

The 'fft' function allows you to specify the number of DFT points to be used by including a second argument:
>> xdft = fft(x,NFFT);
Here 'NFFT' is the number of DFT points. Then, the two-sided FFT can be truncated to a single-sided FFT:
>> xdft = xdft(1:NFFT/2+1);
Next the PSD can be calculated, noting that the zeros used to pad the input do not contribute to the total time of the signal and so 'N', the number of points in the original signal, and not 'NFFT' is used (here 'Fs' is the sampling frequency). At the same time, the contribution of the values that were truncated in the previous step can be included:
>> psdx = (1/(Fs*N)) * abs(xdft).^2;
>> psdx(2:end-1) = 2*psdx(2:end-1);
When finding the corresponding frequencies, 'NFFT' must be used again:
>> freq = 0:Fs/NFFT:Fs/2;