## Rotation and flipping of multidimensional numpy matrices

Question

I have a numpy matrix 'mat', which is 888 * 100 * 100. This represents 888 samples of 100 by 100 grids.

I want to apply a transformation to each grid in the matrix.

I tried mod_mat = np.rot90(mat), but it changed the dimension to 100 * 888 * 100.

Is there a way to carry out the transformations in one go? Or, do I need to iterate over each grid and transform it separately? Thanks.

Show source

## Answers to Rotation and flipping of multidimensional numpy matrices ( 2 )

1. np.rot90 rotates first two dimensions, so you can swap axes 0 and 2, rotate and swap back to achieve what you want. Python iteration probably will be slower, because numpy is a highly optimized low-level code library, so it is usually better to use built-ins.

``````In[9]: import numpy as np
In[10]: x = np.arange(3*2*2).reshape(3, 2, 2)
In[11]: x
Out[11]:
array([[[ 0,  1],
[ 2,  3]],

[[ 4,  5],
[ 6,  7]],

[[ 8,  9],
[10, 11]]])
In[12]: np.rot90(x.swapaxes(0, 2)).swapaxes(0, 2)
Out[12]:
array([[[ 2,  0],
[ 3,  1]],

[[ 6,  4],
[ 7,  5]],

[[10,  8],
[11,  9]]])
``````
2. Here's an approach using `transpose` and `flipping/reversing` the last axis -

``````mat.transpose(0,2,1)[...,::-1]
``````

Runtime test -

``````In [10]: a = np.random.rand(888 , 200 , 200) # Input array

In [11]: %timeit np.rot90(a.swapaxes(0, 2)).swapaxes(0, 2) # @Wolfram's soln
100000 loops, best of 3: 3.87 µs per loop

In [12]: %timeit a.transpose(0,2,1)[...,::-1]
1000000 loops, best of 3: 940 ns per loop
``````