5

I have encountered the following function in MATLAB that sequentially flips all of the dimensions in a matrix:

function X=flipall(X)
    for i=1:ndims(X)
        X = flipdim(X,i);
    end
end

Where X has dimensions (M,N,P) = (24,24,100). How can I do this in Python, given that X is a NumPy array?

rayryeng
  • 102,964
  • 22
  • 184
  • 193
Wajih
  • 793
  • 3
  • 14
  • 31

1 Answers1

6

The equivalent to flipdim in MATLAB is flip in numpy. Be advised that this is only available in version 1.12.0.

Therefore, it's simply:

import numpy as np

def flipall(X):
    Xcopy = X.copy()
    for i in range(X.ndim):
        Xcopy = np.flip(Xcopy, i)
     return Xcopy

As such, you'd simply call it like so:

Xflip = flipall(X)

However, if you know a priori that you have only three dimensions, you can hard code the operation by simply doing:

def flipall(X):
    return X[::-1,::-1,::-1]

This flips each dimension one right after the other.


If you don't have version 1.12.0 (thanks to user hpaulj), you can use slice to do the same operation:

import numpy as np

def flipall(X):
    return X[[slice(None,None,-1) for _ in X.shape]]
rayryeng
  • 102,964
  • 22
  • 184
  • 193
  • 1
    How about this one, X[::-1,::-1,::-1] Will it be the same? – Wajih Sep 15 '16 at 05:58
  • @Wajih Correct. That's assuming that you have three dimensions. The code will work for any amount of dimensions of your `numpy` array. – rayryeng Sep 15 '16 at 05:59
  • Thanks. Python syntax is so confusing at times. Yes the dimension will be 3, so it will work just fine :) – Wajih Sep 15 '16 at 06:00
  • 1
    @Wajih haha! Don't I know it! – rayryeng Sep 15 '16 at 06:01
  • @Wajih btw, you're very welcome and thanks for the accept! – rayryeng Sep 15 '16 at 06:07
  • 3
    `x[[slice(None,None,-1) for _ in x.shape]]` for `x` of unknown dimension. – hpaulj Sep 15 '16 at 06:19
  • @hpaulj Thanks. Didn't know that. I've added that to my post. – rayryeng Sep 15 '16 at 06:26
  • The statement on "this will mutate the array" is wrong, I think. You're creating a new binding. This will change the value that `X` is assigned to. I checked it for the second case compatible with numpy 1.11 at least. You will _have_ to return the array. – Praveen Sep 15 '16 at 06:26
  • @Praveen I'll remove that statement and will explicitly return. Thanks for the correction. – rayryeng Sep 15 '16 at 06:27
  • @Praveen I've also tested. The first way does not create a new binding and it actually does mutate. The second version does. To minimize confusion, for the first version I've simply made a new copy of the array and performed the flipping on that new copy and returned it. – rayryeng Sep 15 '16 at 06:36
  • Surprising. I'd have thought that the view object returned by the `flip` method gets bound to `X`. Thanks for the info, and for checking! – Praveen Sep 15 '16 at 06:38
  • @Praveen yeah it's really weird... ah well. That was a cool experiment to run. You're very welcome! – rayryeng Sep 15 '16 at 06:41