Transpose of a matrix using numpy.ndarray with example

Transpose of a matrix is obtained by flipping the matrix over the main diagonal of the matrix. The transpose() method of the numpy.ndarray can be used to get transpose of a matrix.

Ndarray Updated 15 Apr 2017 1 min read

Overview

  • Transpose of a matrix is achieved by flipping the matrix over its main diagonal.
  • Transpose of a matrix is formed in two steps. In the new matrix,
    • copy the columns of the original matrix as rows.
    • copy the rows of the original matrix as columns.
  • By repeating the transpose operation on the already transposed matrix yields the original matrix.
  • Using the transpose() method of the numpy.ndarray transpose of a matrix can be obtained.

Example

python
import numpy as np

import random

# Populate Array

def FillMatrix(matrix_in):

    for x in range(0, matrix_in.shape[0]):

        for y in range(0, matrix_in.shape[1]):

            matrix_in[x][y] = random.randrange(1, 5)

# Create a matrix1

matrix1 = np.ndarray((3, 3))

# Populate the matrix

FillMatrix(matrix1)

# Create the transpose of the matrix

transposed = matrix1.transpose()

# Print the Matrices

print("Original Matrix:")

print(matrix1)

print("Transpose of Matrix:")

print(transposed)

Output

Output
Original Matrix:

[[ 2.  1.  4.]

 [ 4.  4.  2.]

 [ 2.  2.  3.]]

Transpose of Matrix:

[[ 2.  4.  2.]

 [ 1.  4.  2.]

 [ 4.  2.  3.]]