[Python] How can i do the transpose of a matrix in python? [duplicate]

Discussão em 'Python' iniciado por Stack, Maio 27, 2025.

  1. Stack

    Stack Membro Participativo

    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[j] = matrix[j]

    return matrix


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

    Continue reading...

Compartilhe esta Página