Matlab circshift equivalent in C / C++

Note: The contents have been superceded by a better version at : https://kerpanic.wordpress.com/2016/04/08/more-efficient-ifftshift-fftshift-in-c/

For a better circshift using std::rotate check out  https://github.com/lppier/DSPFunctions

matlablogoRecently I needed this function to replicate Matlab’s circshift, which can do it for 2D arrays. Implemented as follows :

template<typename 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;
   if (ii<0) ii = xdim + ii;
   for (int j = 0; j < ydim; j++) {
     int jj = (j + yshift) % ydim;
     if (jj<0) jj = ydim + jj;
     out[ii * ydim + jj] = in[i * ydim + j];
   }
 }
}


Test Code:

int main(int argc, char **argv)
{
  int* in = (int*)malloc(5*sizeof(int));
  int* out = (int*)malloc(5*sizeof(int));
  for (int i=0; i < 5; i++)
    in[i] = i;
  printArray(in, 5);
  circshift(out, in, 1, 5, 0, -2); //-- +ve == shift right , -ve == shift left
  printArray(out, 5);
  delete in;
  delete out;
  return 0;
}

Hope this is useful to you!

For implementing ifftshift / fftshift using the above circular shift function, please look at : http://stackoverflow.com/questions/34918807/fftshift-ifftshift-in-terms-of-circshift/34919714#34919714

Advertisements

One thought on “Matlab circshift equivalent in C / C++

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s