2

How can I calculate the fft zero-padded to a specific length in Julia? Naturally, I can append zeros to my vector, but that seems awkward.

I cannot find anything about this in the docs, nor does calling methods(fft) seem to bring up any relevant method signatures. I cannot find anything relevant for plan_fft either.

DNF
  • 11,584
  • 1
  • 26
  • 40

2 Answers2

2

I don't think there are any keyword arguments to do this or something like that if thats what you were looking for?

The nextpow2() and nextprod() functions are useful for getting the size of the array to input to fft(). Then you can either create an array of zeros that is a more efficient size and fill it with your data. Or you can append the difference between the ideal-size and your array-size to your array (the former is better if you are computing lots of fft's as then you can reuse the input array by just re-filling it each time).

One-liner from comments datpad = [dat; zeros(eltype(dat), nextprod(length(dat)) - length(dat)]

http://docs.julialang.org/en/release-0.5/stdlib/math/?highlight=fft#signal-processing In case you haven't already checked that out!

Alexander Morley
  • 4,111
  • 12
  • 26
  • It is surprising, given that the padding parameter is very much front and centre in Matlab and Numpy. Padding manually is awkward in the REPL, and allocates extra memory. I guess implementing my own wrapper method that zero-pads is a solution. – DNF Sep 27 '16 at 10:53
  • Yep, if you are going to use often in the REPL then that is probably the way to go. You can do it in one line though `datpad = [dat; zeros(eltype(dat), nextprod(length(dat)) - length(dat)]` – Alexander Morley Sep 27 '16 at 11:51
1

If I am not mistaken, Julia uses FFTW for FFT. I don't remember seeing anything in the FFTW manual about automatically doing zero-padded FFTs without manipulating the input data.

If you are not interested in speed and are only using FFT as a shorthand for the discrete Fourier transform (DFT), you could do the DFT with a DFT function of arbitrary frequency bin sampling or just run the transform manually. It will no longer be an O( N log N ) operation but it does avoid manually padding your original data vector and you can space the sampling of the transform as you need, e.g. oversampling the parts of the spectrum that you are interested in or leaving out the parts that you do not care about.

For example, to make the DFT matrix that samples at frequencies f:

M = exp( -2im*pi * f/Fs * (0:N-1)' )

where Fs is the sampling rate of the data vector and N is the length of the data vector. f is also a vector of frequency values. Apply with matrix multiplication:

y = M * x

If the DFT matrix gets too big, just apply each row of it in a loop.

Petter Friberg
  • 21,252
  • 9
  • 60
  • 109