How do you sequentially flip each dimension in a NumPy array?
<p>I have encountered the following function in MATLAB that sequentially flips all of the dimensions in a matrix:</p>

<pre><code>function X=flipall(X)
    for i=1:ndims(X)
        X = flipdim(X,i);
    end
end
</code></pre>

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

<p>The equivalent to <code>flipdim</code> in MATLAB is <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.flip.html" rel="nofollow"><code>flip</code></a> in <code>numpy</code>.  Be advised that this is only available in version 1.12.0.</p>

<p>Therefore, it's simply:</p>

<pre><code>import numpy as np

def flipall(X):
    Xcopy = X.copy()
    for i in range(X.ndim):
        Xcopy = np.flip(Xcopy, i)
     return Xcopy
</code></pre>

<p>As such, you'd simply call it like so:</p>

<pre><code>Xflip = flipall(X)
</code></pre>

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

<pre><code>def flipall(X):
    return X[::-1,::-1,::-1]
</code></pre>

<p>This flips each dimension one right after the other.</p>

<hr>

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

<pre><code>import numpy as np

def flipall(X):
    return X[[slice(None,None,-1) for _ in X.shape]]
</code></pre>

python matlab numpy flip