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?

5
  • What is the format of X in Python? Is it a list or perhaps a NumPy array? There is too little information to answer your question. Commented Sep 15, 2016 at 5:39
  • @rayryeng - This has to be a numpy array Commented Sep 15, 2016 at 5:46
  • Thanks. You didn't make that clear in your post. Commented Sep 15, 2016 at 5:48
  • @rayryeng - Just edited the question :) Commented Sep 15, 2016 at 5:50
  • from here: X[[slice(None, None, -1)] * X.ndim] Commented Aug 13, 2018 at 8:07

1 Answer 1

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]]
Sign up to request clarification or add additional context in comments.

12 Comments

How about this one, X[::-1,::-1,::-1] Will it be the same?
@Wajih Correct. That's assuming that you have three dimensions. The code will work for any amount of dimensions of your numpy array.
Thanks. Python syntax is so confusing at times. Yes the dimension will be 3, so it will work just fine :)
@Wajih haha! Don't I know it!
x[[slice(None,None,-1) for _ in x.shape]] for x of unknown dimension.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.