Program to compute transpose of a matrix using Python

Introduction

In this section of programming, we are going to compute the transpose of a matrix.

Program to compute transpose of a matrix

Program

import numpy as nump

X = [[6, 8, 3], [2, 1, 10], [4, 4, 7]]

# Using numpy

result1 = nump.transpose(X)

print("Transpose of matrix using matrix numpy transpose:")

print(result1)

print("\n")




# Using zip()

result2 = zip(*X)

print("Transpose of matrix using zip():")

for k in result2:

    print(k)

print("\n")




# Using list comprehension

result3 = [[X[j][i] for j in range(len(X))] for i in  range(len(X[0]))]

print("Transpose of matrix using list comprehension:")

for l in result3:

    print(l)

Output

Program to compute transpose of a matrix Output

Explanation

In the above code, we have created a matrix X with size 3 x 3 . To find the transpose of matrix, python numpy package provides an in-built method “transpose” to compute the transpose of multi-dimensional matrix (we can also write “<matrix-name>.T” instead of numpy.transpose(<matrix-name>) in line 5).

Similarly, the nested list comprehension traverse over each element in column major order(column major and row major are methods to store multi-dimensional arrays in a linear manner).

The third way we used to compute the matrix is using zip(). Firstly, we unzip(by using *) the matrix and then zipped it to get the transpose.

Author

  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.

    View all posts

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.