Transpose Of A Matrix Using Numpy.ndarray With Example

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.ndarry transpose of a matrix can be obtained.

 

Example:

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:

Original Matrix:

[[ 2.  1.  4.]

 [ 4.  4.  2.]

 [ 2.  2.  3.]]

Transpose of Matrix:

[[ 2.  4.  2.]

 [ 1.  4.  2.]

 [ 4.  2.  3.]]


Copyright 2022 © pythontic.com