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?
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]]