0

Given the matrix

matrix = [[2, None],
       [2, None]]

I need to compute the transpose of this. I did the following:

def transpose(matrix):
    # Makes a copy of the matrix
    result = matrix
    # Computes tranpose
    for i in range(2):
        for j in range(2):
            result[j][i] = matrix[i][j]

    return result

But this gives me the false result:

[[2, None],
[None, None]]

while it should be

[[2, 2],
[None, None]]

Can someone tell me where I went wrong with my code?

Kamil
  • 227
  • 4
  • 14

4 Answers4

4

You a referencing to the same matrix, try initializing a new one:

def transpose(matrix):
    # Makes a copy of the matrix
    result = [[None]* len(x) for x in matrix]
    # Computes tranpose
    for i in range(2):
        for j in range(2):
            result[i][j] = matrix[j][i]

    return result

You can also do it for a generic matrix using list comprehesion

def transpose(matrix):
    return [[matrix[i][j] for i in range(len(matrix[j]))] for j in range(len(matrix))]
Netwave
  • 40,134
  • 6
  • 50
  • 93
3

The problem is that the variable result refers to matrix, that is, you do not make a copy, so in the for-loop you actually also change matrix. You can solve this by making a copy of matrix in result with list:

result = [list(x) for x in matrix]

See the question: How to clone or copy a list?


Note that an easier way is to use NumPy:

import numpy as np
matrix = np.matrix([[2, None],[2, None]])

then use matrix.T to get the transpose:

matrix([[2, 2],
        [None, None]], dtype=object)
Community
  • 1
  • 1
agold
  • 6,140
  • 9
  • 38
  • 54
1
# We can use the below method also:
matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
mat_trans = []
trans = []
trans1 = []
trans2 = []
trans3 = []
for row in matrix:
    for i in range(4):
        if i == 0:
            trans.append(row[i])
        if i == 1:
            trans1.append(row[i])
        if i == 2:
            trans2.append(row[i])
        if i == 3:
            trans3.append(row[i])
mat_trans.append(trans)
mat_trans.append(trans1)
mat_trans.append(trans2)
mat_trans.append(trans3)
trans = []
print(mat_trans)
0

Assuming that the matrix is rectangular (i.e. same list size in all one-D arrays), one can simply write a transpose as the following.

def transpose(matrix):
    num_rows = len(matrix)
    num_cols = len(matrix[0])

    result = []
    for j in range(num_cols):
        rowresult = []
        for i in range(num_rows):
            rowresult.append(matrix[i][j])
        result.append(rowresult)

    return result

Note: This is not the most efficient implementation.

AnupamB
  • 31
  • 4