Julia DSP Periodograms n > nfft is error, why?

Viewed 68

This

n = length(s)
# n = 25920169
nfft = 8192
noverlap = Int64(floor(nfft/2))
window = hanning(nfft)
#sp = spectrogram(s, n, noverlap; nfft=nfft, fs=1, window=window)
sp = periodogram(s; nfft=nfft, fs=1, window=window)

throws the error

nfft must be >= n

But the documentation says:

If length(s) < nfft, then the input is padded with zeros. 

Doesn't it mean that nfft < n should be correct?

1 Answers

I think that the FFT length nfft should be greater than the signal length n to prevent aliasing.

The periodogram function uses FFT internally, where the length is denoted as nfft. In theory, when using FFT, the signal in both time domain and frequency domain are discrete and periodic, where the period is given by nfft. So, if you specify an nfft that is less than the signal length n, this actually introduces aliasing in the time domain to make the signal periodic with nfft.

For example, if you have a sequence 1 2 3 4 5, assuming that your period is also 5, you have

1 2 3 4 5
          1 2 3 4 5
                    1 2 3 4 5
--------------------------------
      ... 1 2 3 4 5 ...

i.e., the original sequence. Now assume you have a period of 3, then it looks like

1 2 3 4 5
      1 2 3 4 5
            1 2 3 4 5
------------------------
  ... 5 7 3 ...

When you take FFT of this sequence with n > nfft, you are working with this aliased sequence.

You can manually allow for n > nfft by applying the wrap(x,nfft) as bellow and feeding its output to periodogram, MATLAB does exactly that.

function wrap(x,nfft)
    y = zeros(eltype(x),nfft)
    for (i,xi) in enumerate(x)
        y[mod1(i,nfft)] += xi
    end
    y
end

For example:

wrap(1:5,3)
3-element Vector{Int64}:
 5
 7
 3
Related