Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating a 5D array in the last 2 dimensions

I have a 5D array 'a', of size (3,2,2,2,2).

import numpy as np
a = np.arange(48).reshape(3,2,2,2,2)
a[0,0,0]:
array([[0, 1],
       [2, 3]])

What I want to do is rotate this 5D array by 180 degrees, but only in the last two dimensions, without their positions changed. So output[0,0,0] should look like this:

out[0,0,0]:
array([[3, 2],
       [1, 0]])

What I have tried:

out = np.rot90(a, 2)
out[0,0,0]:
array([[40, 41],
       [42, 43]])

The rot90 function apparently rotates the whole array.

Note: I want to avoid using for loops if possible

like image 387
Babak Avatar asked Oct 18 '22 18:10

Babak


2 Answers

To rotate the last two axes 180 degrees, pass axes=(-2, -1) to np.rot90:

>>> a180 = np.rot90(a, 2, axes=(-2, -1))
>>> a180[0, 0, 0]
array([[3, 2],
       [1, 0]])

If your version of NumPy does not have the axes parameter with np.rot90, there are alternatives.

One way is with indexing:

a180 = a[..., ::-1, ::-1]

rot90 flips the first two axes of the array, therefore to use it you'd need to transpose (to reverse the axes), rotate, and transpose back again. For example:

np.rot90(a.T, 2).T
like image 77
Alex Riley Avatar answered Oct 23 '22 09:10

Alex Riley


If I understood the question correctly, you could reverse the arrangement of the elements along the last two axes, like so -

a[:,:,::-1,::-1]

You can also reshape to a 2D array merging the last two axes as the last axis, then reverse elements along it and reshape back, like so -

a.reshape(-1,np.prod(a.shape[-2:]))[:,::-1].reshape(a.shape)

Sample run -

In [141]: a[0][0]
Out[141]: 
array([[57, 64, 69],
       [41, 28, 89]])

In [142]: out1 = a[:,:,::-1,::-1]

In [143]: out2 = a.reshape(-1,np.prod(a.shape[-2:]))[:,::-1].reshape(a.shape)

In [144]: out1[0][0]
Out[144]: 
array([[89, 28, 41],
       [69, 64, 57]])

In [145]: out2[0][0]
Out[145]: 
array([[89, 28, 41],
       [69, 64, 57]])
like image 42
Divakar Avatar answered Oct 23 '22 10:10

Divakar