How can i do the transpose of a matrix in python?

Question:

I am making a function in python in which when taking a matrix A, it returns a matrix B with swapped rows and columns, example:

if i enter this matrix:

1  2  3  4 
5  6  7  8
9  10 11 12
13 14 15 16

Should return

1 5 9  13
2 6 10 14
3 7 11 15
4 8 12 16

but what I get is:

array([[ 1,  5,  9, 13],
       [ 5,  6, 10, 14],
       [ 9, 10, 11, 15],
       [13, 14, 15, 16]])

I don’t understand why, could someone help me understand this error and how can I solve it?

my code:

def transpose(matrix):

    for i in range(matrix.shape[0]):
        for j in range(matrix.shape[1]):
            matrix[i][j] = matrix[j][i]
            
    return matrix

(I can’t use default functions like transpose, I have to code)

Asked By: Lauuu

||

Answers:

You can use numpy.transpose to transpose a matrix.

As for why your code is not working is because your program does the follow assignments in a loop:

matrix[0][2] = matrix[2][0] # writes 9
...
matrix[2][0] = matrix[0][2] # writes 9 instead of 3 because matrix[0][2] has previously been updated

So to fix this you can use an intermediate variable like output_matrix in this example:

def transpose(matrix):
    output_matrix = np.zeros_like(matrix)
    for i in range(matrix.shape[0]):
        for j in range(matrix.shape[1]):
            output_matrix[i][j] = matrix[j][i]
            
    return output_matrix
Answered By: tiger

This line

matrix[i][j] = matrix[j][i]

is your issue.

For example, when i = 1 and j = 2, you set matrix[1][2] to 10 because matrix[2][1] is 10. When you come around the next time to i = 2 and j = 1, you set matrix[2][1] to 10 because matrix[1][2] was set to 10 even though it was originally 7, it doesn’t keep a memory of the previous value.

Depending on if you want the function to mutate the original matrix or return a new matrix with changes values (but keep the original) will change how you create this function.

To mutate the original

def transpose(matrix):
    matrix2 = numpy.copy(matrix)
    for i in range(matrix.shape[0]):
        for j in range(matrix.shape[1]):
            matrix[i][j] = matrix2[j][i]
            
    return matrix

To return a new array

def transpose(matrix):
    matrix2 = numpy.copy(matrix)
    for i in range(matrix.shape[0]):
        for j in range(matrix.shape[1]):
            matrix2[i][j] = matrix[j][i]
            
    return matrix2
Answered By: Samathingamajig

zip can do this for you. Unpack the list and pass sub lists as arguments to the zip:

lst = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16],
]

transposed = list(zip(*lst))
for i in transposed:
    print(i)

output:

(1, 5, 9, 13)
(2, 6, 10, 14)
(3, 7, 11, 15)
(4, 8, 12, 16)
Answered By: S.B
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.