In this section of programming, we are going to compute the transpose of a matrix.
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))] print("Transpose of matrix using list comprehension:") for l in result3: print(l)
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.