Example HTML page

A Python program to find Transpose of a matrix

(If you are viewing this page in mobile, kindly switch to desktop view for better visual appearance).

In this post we will see how to find Transpose of a matrix.

The interchanging of rows and columns is said as “Transpose of a matrix”. In Python, a matrix is nothing but a list of lists of equal number of items. We can denote transpose of matrix as T. The element at ith row and jth column in T will be placed at jth row and ith column in T’. Therefore if T is a 3X2 matrix, then T will be a 2×3 matrix which is considered as a resultant matrix.

There are different ways to find transpose of a matrix. In this post we will see the two ways to find it.

Way 1: Using nested lists

We can implement a matrix as a nested list (list inside a list).

#Program

M = [[2, 3],
	  [4, 5],
	  [6, 7]]
Trans_M = [[0, 0, 0],
	   [0, 0, 0]]
for a in range(len(M)):
    for b in range(len(M[0])):
        Trans_M[b][a] = M[a][b]
for T in Trans_M:
    print(T)

Output

[2, 4, 6]
[3, 5, 7]

Explanation

In the above program we have taken M = [[2, 3], [4, 5], [6, 7]] represents a 3×2 matrix. To transpose ‘M’ matrix we have taken 2×3 matrix with null elements and is stored in Trans_M variable. Every element in the row and column get iterated using ‘for’ loop. Now check the size of the matrix with the instruction Trans_M[b][a] = M[a][b]”. If it evaluates to true then the immediate “for” loop get iterated and finally prints the transpose of matrix “M”.

Way 2: Using list comprehension

We can also find transpose of a matrix by using List comprehension concept. Usually List comprehension is used to write the code in short i.e it helps in reduction of lines of codes. Here we are finding transpose of a matrix at a single line. Let’s see how it works.

#Program

A = [[11,3],
    [7 ,5],
    [8 ,13]]
output = [[A[p][q] for p in range(len(A))] for q in range(len(A[0]))]
for B in output:
   print(B)

Output

[11, 7, 8]

[3, 5, 13]

 

Example HTML page

Leave a Reply

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

Pin It on Pinterest