2

what is the exact equivalent of this MATLAB line code in C++ and using FFTW?

fftshift(fft(x,4096)));

note: X is an array of 4096 double data.

now I use these lines of code in c++ and FFTW to compute fft

int n = 4096
fftw_complex *x;
fftw_complex *y;
x = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * n);
y = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * n);

for (int i=0; i<n; i++)
{
       x[i][REAL] = MyDoubleData[i];
       x[i][IMAG] = 0;
}

fftw_plan plan = fftw_plan_dft_1d(n, x, y, FFTW_FORWARD, FFTW_ESTIMATE);

fftw_execute(plan);
fftw_destroy_plan(plan);
fftw_cleanup();

It is just equivalent of FFT function in MATLAB. Is there any equivalent function for FftShift in FFTW library?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

2 Answers2

1

The FFTW function calls you've provided would be the equivalent of fft(x,4096). If x is real, matlab knows to give you the conjugate symmetric FFT (I think). If you want to do this with FFTW, you need to use the r2c and c2r functions (real-to-complex/complex-to-real).

You have to do the shift yourself. You can do direct substitution (poor performance, but should be intuitive)

for (int i=0; i<n; i++)
{
    fftw_complex tmp;
    int src = i;
    int dst = (i + n/2 - 1) % n;

    tmp=y[src];
    y[src]=x[dst];
    y[dst]=tmp;
}

Alternatively use a couple memcpy's (and/or memmove's) or modify your input data

Gavin Portwood
  • 1,217
  • 8
  • 9
  • They are NOT equivalent to fftshift( fft( x ) ), they are equivalent to fft( x ) – Elias Oct 01 '17 at 04:16
  • 1
    The crossed out comment about real input is valid. It doesn't related to the `fftshift` part, but it's still useful. The code shown here for `fftshift` only works for even-sized arrays. For odd-sized arrays it won't shift the 0-frequency to the leftmost bin. See here for a few different correct implementations: https://stackoverflow.com/questions/5915125/fftshift-ifftshift-c-c-source-code – Cris Luengo Apr 17 '18 at 15:28
1

The output of the fftw is stored base on following format of frequencies sequence:

[0....N-1]

Where N is number of frequencies and is oven. And fftshift change it to:

[-(N-1)/2,..., 0..., (N-1)/2]

but you should note that fftw output has equivalent as:

[0,.., N-1] is same as [0,...,(N-1)/2,-(N-1)/2,...,-1]

This means that in DFT, frequency -i is same as N-i.

Fayyaz
  • 33
  • 4