Hamid Reza Arzaghi
Hamid Reza Arzaghi

Reputation: 368

FFT and FFTShift of matlab in FFTW library c++

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?

Upvotes: 2

Views: 4733

Answers (2)

Fayyaz
Fayyaz

Reputation: 33

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 even. 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.

Upvotes: 1

Gavin Portwood
Gavin Portwood

Reputation: 1217

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

Upvotes: 1

Related Questions