Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fftshift/ifftshift C/C++ source code [closed]

Tags:

c++

c

matlab

fft

Does anyone know if there is any free and open source library that has implemented these two functions the way they are defined in matlab?

Thanks

like image 974
Derek Avatar asked May 06 '11 17:05

Derek


People also ask

What is ifftshift in matlab?

Y = fftshift( X ) rearranges a Fourier transform X by shifting the zero-frequency component to the center of the array. If X is a vector, then fftshift swaps the left and right halves of X . If X is a matrix, then fftshift swaps the first quadrant of X with the third, and the second quadrant with the fourth.

Why is Fftshift used?

fftshift (MATLAB Functions) Y = fftshift(X) rearranges the outputs of fft , fft2 , and fftn by moving the zero-frequency component to the center of the array. It is useful for visualizing a Fourier transform with the zero-frequency component in the middle of the spectrum.


2 Answers

FFTHIFT / IFFTSHIFT is a fancy way of doing CIRCSHIFT. You can verify that FFTSHIFT can be rewritten as CIRCSHIFT as following. You can define macros in C/C++ to punt FFTSHIFT to CIRCSHIFT.

A = rand(m, n);
mm = floor(m / 2);
nn = floor(n / 2);
% All three of the following should provide zeros.
circshift(A,[mm, nn]) - fftshift(A)
circshift(A,[mm,  0]) - fftshift(A, 1)
circshift(A,[ 0, nn]) - fftshift(A, 2) 

Similar equivalents can be found for IFFTSHIFT.

Circular shift can be implemented very simply with the following code (Can be improved with parallel versions ofcourse).

template<class ty>
void circshift(ty *out, const ty *in, int xdim, int ydim, int xshift, int yshift)
{
  for (int i = 0; i < xdim; i++) {
    int ii = (i + xshift) % xdim;
    for (int j = 0; j < ydim; j++) {
      int jj = (j + yshift) % ydim;
      out[ii * ydim + jj] = in[i * ydim + j];
    }
  }
}

And then

#define fftshift(out, in, x, y) circshift(out, in, x, y, (x/2), (y/2))
#define ifftshift(out, in, x, y) circshift(out, in, x, y, ((x+1)/2), ((y+1)/2))

This was done a bit impromptu. Bear with me if there are any formatting / syntactical problems.

like image 72
Pavan Yalamanchili Avatar answered Sep 19 '22 16:09

Pavan Yalamanchili


Normally, centering the FFT is done with v(k)=v(k)*(-1)**k in the time domain. Shifting in the frequency domain is a poor substitute, for mathematical reasons and for computational efficiency. See pp 27 of: http://show.docjava.com/pub/document/jot/v8n6.pdf

I am not sure why Matlab documentation does it the way they do, they give no technical reference.

like image 39
Douglas Lyon Avatar answered Sep 19 '22 16:09

Douglas Lyon