Reputation: 53
Does anyone can tell me how to use Numpy to reshape the Matrix
[1,2,3,4]
[5,6,7,8]
[9,10,11,12]
[13,14,15,16]
to
[16,15,14,13]
[12,11,10,9]
[8,7,6,5]
[4,3,2,1]
Thanks:)
python 3.8 numpy 1.21.5
an example of my matrixs:
[[ 1.92982258e+00 1.96782439e+00 2.00233048e-01 3.95128552e-01
4.21665915e-01 -1.10885581e-01 3.15967524e-01 1.86851601e-01]
[ 5.82581567e-01 3.85242821e-01 6.52345512e-01 6.96774921e-01
4.46925274e-01 1.10208991e-01 -1.78544580e-02 2.63118328e-01]
[ 1.18591189e-01 -8.87084649e-02 3.35701398e-01 3.81145692e-01
2.11622312e-02 3.10028567e-01 2.04480529e-01 4.45985566e-01]
[ 5.59840625e-01 2.01962111e-01 5.34994738e-01 2.48421290e-01
2.42632687e-01 2.13238611e-01 3.96632085e-01 4.94549692e-01]
[-7.69809051e-02 -3.00706661e-04 1.44790257e-01 3.49158021e-01
1.10096226e-01 2.03164938e-01 -3.45361600e-01 -3.33408510e-02]
[ 2.33273192e-01 4.39144490e-01 -6.11938054e-02 -6.93128853e-02
-9.55871298e-02 -1.97338746e-02 -6.54788754e-02 2.81574199e-01]
[ 6.61742595e-01 4.04149752e-01 2.33536310e-01 8.86332882e-02
-2.21808751e-01 -5.48789656e-03 5.49503834e-01 -1.22011728e-01]
[-9.58502481e-03 2.36994437e-01 -1.28777627e-01 3.99751917e-01
-1.92452263e-02 -2.58119080e-01 3.40399940e-01 -2.20455571e-01]]
Upvotes: 3
Views: 53
Reputation: 92440
You can rotate the matrix with numpy.rot90()
. To get two rotations as your example, pass in k=2
:
import numpy as np
a = np.array([
[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16],
])
np.rot90(a, k=2)
returning:
array([[16, 15, 14, 13],
[12, 11, 10, 9],
[ 8, 7, 6, 5],
[ 4, 3, 2, 1]])
Note the docs that say it returns a view of the original. This means the rotated matrix shares data with the original. Mutating one effects the other.
Upvotes: 4