3

Basically, I'm looking for a generalization of flipud and fliplr to flip the i-th dimension of an nd-array.

When the dimension to be flipped is the first one, I guess I can use

function flipped = flipfirst(ndarr)
    sz = size(ndarr);
    flipped = reshape(flipud(reshape(ndarr, sz(1), [])), sz);
end

Likewise, if the dimension to be flipped is the last one, I could use

function flipped = fliplast(ndarr)
    sz = size(ndarr);
    flipped = reshape(fliplr(reshape(ndarr, [], sz(end))), sz);
end

I'm sure that I can code something more general, with calls to permute and whatnot, but is there anything built-in for this?

I'm not sure how expensive it is to do all the reshape-ing above, but if it is, I'd also be interested in more efficient non-built-in approaches.

kjo
  • 33,683
  • 52
  • 148
  • 265

4 Answers4

8

If you have R2013b+ you should use the new flip function:

A = rand(2,2,2);
B = flip(A,3);

For older versions you can use flipdim:

A = rand(2,2,2);
B = flipdim(A,3);

Type edit flipdim in your command window to see the clever code for flipdim.

horchler
  • 18,384
  • 4
  • 37
  • 73
  • 1
    Good links. I wonder how `flip` "provides a faster and more memory efficient alternative" and how significant of an improvement it gives. In any case, I'll be sure to "flip" from `flipdim` to `flip`. – chappjc Feb 23 '14 at 01:15
  • @chappjc: `flip` is a native function whereas `flipdim` is not. Is some simple timing tests `flip` is about 2.5 times faster for large arrays on my machine. In the case of large arrays at least, `flipdim` needs to build a big index vector, but there are likely other C-level optimizations. – horchler Feb 23 '14 at 15:11
5

You can also flip an array by using the time reversal property of the Discrete Fourier Transform. The code below works for any number of dimensions, but we demonstrate it with a 2D array because it's easier to examine the results.

A = magic(8);

d = 1; % dimension along which to flip

% Create frequency array w, we need it to go along dimension d
sz = size(A, d);
w = 2*pi * (0:sz-1) / sz;
w = shiftdim(w(:), 1-d);

% The actual time reversal property:
B = ifft( conj(fft(A, [], d)) .* exp(1j*w), [], d, 'symmetric');

(yes, this is overly complicated and ridiculously expensive compared to flip, but it's fun!)

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
4

From flipdim:

Flip array along specified dimension

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
2

Mostly for fun too...

This uses a comma-separated list generated from a cell array, together with the not very well known fact that you can use ':' as an index:

A = rand(3,4,5);                  % input array
dim = 2;                          % dimension to flip along
c = repmat({':'}, 1, ndims(A));
c{dim} = size(A, dim):-1:1;
B = A(c{:});
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147