Programming Previous page   Next Page

Fast Fourier Transform Example

The fftshift function swaps the left and right halves of each dimension of an array. For a simple vector such as [0 2 4 6 8 10] the output would be [6 8 10 0 2 4]. For a multidimensional array, fftshift performs this swap along each dimension.

fftshift uses vectors of indices to perform the swap. For the vector shown above, the index [1 2 3 4 5 6] is rearranged to form a new index [4 5 6 1 2 3]. The function then uses this index vector to reposition the elements. For a multidimensional array, fftshift must construct an index vector for each dimension. A comma-separated list makes this task much simpler.

Here is the fftshift function:

The function stores the index vectors in cell array idx. Building this cell array is relatively simple. For each of the N dimensions, determine the size of that dimension and find the integer index nearest the midpoint. Then, construct a vector that swaps the two halves of that dimension.

By using a cell array to store the index vectors and a comma-separated list for the indexing operation, fftshift shifts arrays of any dimension using just a single operation: y = x(idx{:}). If you were to use explicit indexing, you would need to write one if statement for each dimension you want the function to handle:

Another way to handle this without a comma-separated list would be to loop over each dimension, converting one dimension at a time and moving data each time. With a comma-separated list, you move the data just once. A comma-separated list makes it very easy to generalize the swapping operation to an arbitrary number of dimensions.

Previous page  How to Use the Comma-Separated List Program Control Statements Next page

© 1994-2005 The MathWorks, Inc.