23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Comma-Separated Lists<br />

numDims = ndims(x);<br />

idx = cell(1, numDims);<br />

for k = 1:numDims<br />

m = size(x, k);<br />

p = ceil(m/2);<br />

idx{k} = [p+1:m 1:p];<br />

end<br />

y = x(idx{:});<br />

The function stores the index vectors in cell array idx. Building this cell array<br />

is relatively simple. For each of the N dimensions, determine the size of that<br />

dimension and find the integer index nearest the midpoint. Then, construct a<br />

vector that swaps the two halves of that dimension.<br />

By using a cell array to store the index vectors and a comma-separated list<br />

for the indexing operation, fftshift shifts arrays of any dimension using<br />

just a single operation: y = x(idx{:}). If you were to use explicit indexing,<br />

you would need to write one if statement for each dimension you want the<br />

function to handle:<br />

if ndims(x) == 1<br />

y = x(index1);<br />

else if ndims(x) == 2<br />

y = x(index1, index2);<br />

end<br />

Another way to handle this without a comma-separated list would be to loop<br />

over each dimension, converting one dimension at a time and moving data<br />

each time. With a comma-separated list, you move the data just once. A<br />

comma-separated list makes it very easy to generalize the swapping operation<br />

to an arbitrary number of dimensions.<br />

3-87

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!