How to reorder the matrix
Question:
Does anyone could tell me how to reorder the matrix:
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]]
To:
[[15, 10, 5],
[14, 9, 4],
[13, 8, 3],
[12, 7, 2],
[11, 6, 1]]
Answers:
Here is how you can use the zip()
method to transpose your matrix:
m = [[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]]
print([list(i)[::-1] for i in zip(*m)][::-1])
Output:
[[15, 10, 5],
[14, 9, 4],
[13, 8, 3],
[12, 7, 2],
[11, 6, 1]]
The index [::-1]
reverses the array.
I’d suggest using numpy, like so:
import numpy as np
matrix = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]])
transformed_matrix = matrix[::-1].T[::-1]
# array([[15, 10, 5],
# [14, 9, 4],
# [13, 8, 3],
# [12, 7, 2],
# [11, 6, 1]])
matrix[::-1]
gives you the original matrix in reverse order (i.e. [11, 12, 13...]
first and [1, 2, 3...]
last).
Taking the transpose of that with .T
rotates the matrix about – swapping rows and columns.
Lastly, indexing the transpose with [::-1] reverses the order, putting [15, 14, 13...]
first and [5, 4, 3...]
last.
Since you have tagged the question numpy
, I surmise that those are numpy matrix, and you are looking for a numpy solution (otherwise, if those are lists, Ann’s zip is the correct solution).
For numpy you can
M[::-1,::-1].T
Example
M=np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]])
M[::-1,::-1].T
returns
array([[15, 10, 5],
[14, 9, 4],
[13, 8, 3],
[12, 7, 2],
[11, 6, 1]])
as expected
Does anyone could tell me how to reorder the matrix:
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]]
To:
[[15, 10, 5],
[14, 9, 4],
[13, 8, 3],
[12, 7, 2],
[11, 6, 1]]
Here is how you can use the zip()
method to transpose your matrix:
m = [[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]]
print([list(i)[::-1] for i in zip(*m)][::-1])
Output:
[[15, 10, 5],
[14, 9, 4],
[13, 8, 3],
[12, 7, 2],
[11, 6, 1]]
The index [::-1]
reverses the array.
I’d suggest using numpy, like so:
import numpy as np
matrix = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]])
transformed_matrix = matrix[::-1].T[::-1]
# array([[15, 10, 5],
# [14, 9, 4],
# [13, 8, 3],
# [12, 7, 2],
# [11, 6, 1]])
matrix[::-1]
gives you the original matrix in reverse order (i.e. [11, 12, 13...]
first and [1, 2, 3...]
last).
Taking the transpose of that with .T
rotates the matrix about – swapping rows and columns.
Lastly, indexing the transpose with [::-1] reverses the order, putting [15, 14, 13...]
first and [5, 4, 3...]
last.
Since you have tagged the question numpy
, I surmise that those are numpy matrix, and you are looking for a numpy solution (otherwise, if those are lists, Ann’s zip is the correct solution).
For numpy you can
M[::-1,::-1].T
Example
M=np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]])
M[::-1,::-1].T
returns
array([[15, 10, 5],
[14, 9, 4],
[13, 8, 3],
[12, 7, 2],
[11, 6, 1]])
as expected