Home > OS >  Making rows in a matrix vertical
Making rows in a matrix vertical

Time:11-02

I am trying to take the input of this (4x4) matrix:

1.0 2.0 3.0 4.0

5.0 6.0 7.0 8.0

9.0 10.0 11.0 12.0

13.0 14.0 15.0 16.0

and make it appear as:

1.0 5.0 9.0 13.0

2.0 6.0 10.0 14.0

3.0 7.0 11.0 15.0

4.0 8.0 12.0 16.0

I need to write the code in such a way that it only works for an NxN matrix. I thought I may have to do a nested for in loop but I'm confused on exactly how to make it work correctly. If you could help me that would be great!

CodePudding user response:

What you are trying to do is to take the transpose of the matrix. Transposing a matrix means changing all columns into rows (or equivalently, rows into columns). It is easily achieved with numpy:

>>> import numpy as np
>>> a = np.random.randint(10, size=(5, 5))
>>> a
array([[3, 3, 4, 9, 8],
       [9, 0, 0, 5, 6],
       [4, 1, 2, 4, 5],
       [2, 9, 0, 8, 0],
       [9, 9, 2, 3, 0]])
>>> a.T
array([[3, 9, 4, 2, 9],
       [3, 0, 1, 9, 9],
       [4, 0, 2, 0, 2],
       [9, 5, 4, 8, 3],
       [8, 6, 5, 0, 0]])
>>> np.transpose(a)
array([[3, 9, 4, 2, 9],
       [3, 0, 1, 9, 9],
       [4, 0, 2, 0, 2],
       [9, 5, 4, 8, 3],
       [8, 6, 5, 0, 0]])

To do it with more manually, for example

>>> import numpy as np
>>> matrix = np.array([
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9],
    ])
>>> transposed_matrix = np.empty((3, 3))
>>> for i in range(3):
...     transposed_matrix[:, i] = matrix[i, :]
>>> transposed_matrix
array([[1. 4. 7.]
       [2. 5. 8.]
       [3. 6. 9.]])

or completely without numpy (probably many ways to do this, and probably more clever ways than I did too! =)):

>>> matrix = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9],
    ]
>>> transposed_matrix = []
>>> for i in range(3):
...     tmp = []
...     for j in range(3):
...         tmp.append(matrix[j][i])
...     transposed_matrix.append(tmp)
>>> transposed_matrix
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
  • Related