Numpy: Rotate Sub Matrix M Of M
If I knew the dimensions of each square submatrix m (2x2), and that the dimensionality of a large square matrix M was evenly divisible by the dimensionality m: M modulo m == 0. Is
Solution 1:
Here's an approach using reshape
and transpose
-
m,n = M.shape
out = M.reshape(m//2,2,n//2,2)[...,::-1].transpose(0,3,2,1).reshape(m,n)
Sample run -
In [246]: M
Out[246]:
array([[51, 70, 59, 38, 84, 18],
[80, 25, 76, 43, 80, 48],
[92, 98, 46, 14, 65, 47],
[73, 31, 32, 79, 87, 70]])
In [247]: m,n = M.shape
In [248]: M.reshape(m//2,2,n//2,2)[...,::-1].transpose(0,3,2,1).reshape(m,n)
Out[248]:
array([[70, 25, 38, 43, 18, 48],
[51, 80, 59, 76, 84, 80],
[98, 31, 14, 79, 47, 70],
[92, 73, 46, 32, 65, 87]])
If you have to use np.rot90
, which works only on the first two axes, we need to use transpose
twice, like so -
rot_arr = np.rot90(M.reshape(m//2,2,n//2,2).transpose(1,3,0,2),1)
out = rot_arr.transpose(2,0,3,1).reshape(m,n)
Post a Comment for "Numpy: Rotate Sub Matrix M Of M"