0

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]]
Red
  • 26,798
  • 7
  • 36
  • 58
Nobody
  • 53
  • 5
  • For a numpy array this needs a `transpose` and one or more axis `reverse`. There are `flip` and `rot90` functions that some or all of this. – hpaulj Nov 07 '22 at 00:28

3 Answers3

2

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.

Vin
  • 929
  • 1
  • 7
  • 14
  • I can't understand why, but `M[::-1].T[::-1]` is slightly slower than `M[::-1,::-1].T` (order of 600 vs 700 μs. Not much difference. But big enough to be sure it is not just random) – chrslg Nov 07 '22 at 00:35
  • That's really interesting! Thanks for taking the time to comparing the two like that - given me something to think about! – Vin Nov 07 '22 at 01:33
2

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

chrslg
  • 9,023
  • 5
  • 17
  • 31
0

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.

Red
  • 26,798
  • 7
  • 36
  • 58