Skip to content

In Place Transpose of a Square Matrix

A square matrix can be transposed in place by just swapping elements along the diagonals. The trick is to traverse only one side of the diagonal.

The code only iterates over the lower triangle ( lower half over the diagonal excluding the diagonal itself). When you iterate over columns, iterate over [o,curr_row).

For upper triangle iterate over [curr_row+1,n)

[
  00  01   02  03
 *10  11   12  13
 *20 *21   22  23
 *30 *31  *32  33
]
Transposing a square matrix
def transpose(matrix) :
    """
    Transpose an n*n matrix
    """
    n = len(matrix)
    try :
        assert n == len(matrix[0])
    except AssertionError :
        print("Not a square matrix")
        raise

    for r in range(n) :
        #for c in range(r+1, n) : # Iterate over the upper triangle
        for c in range(r) : # Iterate over the lower triangle
            print(f"Swapping ({r},{c}) with ({c},{r})")
            matrix[r][c], matrix[c][r] = matrix[c][r],matrix[r][c]

    return matrix

if __name__ == "__main__" :
    matrix = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]

    print("Original Matrix:")
    for row in matrix:
        print(row)

    transposed_matrix = transpose(matrix)
    print("\nTransposed Matrix:")
    for row in transposed_matrix:
        print(row)

If the matrix is not square, then for an input array of m*n, you will have to allocate a separate target array of dimensions n*m and copy over each element to the target array : src[r][c] = target[c][r]