In this Python program to transpose a matrix. Transpose of a matrix is the interchanging of rows and columns. In other words, Transpose of a matrix means converting rows into columns and columns into rows. It is denoted as “X” matrix. The element at ith row and jth column in X will be placed at jth row and ith column in “X”. So if X is a 3x2 matrix, “X” will be a 2x3 matrix.
Here is the code of the program to transpose a matrix.
# Program to transpose a matrix using a nested loop
# 2x3 Matrix
X = [[6,7],
[4 ,5],
[3 ,8]]
# Output matrix is 3x2
result = [[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]
print("\nOutput after Transpose Matrix")
for r in result:
print(r)
Output after Transpose Matrix
[6, 4, 3]
[7, 5, 8]
# Program to transpose a matrix using list comprehension
# 2x3 Matrix
X = [[6,7],
[4 ,5],
[3 ,8]]
result = [[X[j][i] for j in range(len(X))] for i in range(len(X[0]))]
print("\nOutput after Transpose Matrix")
for r in result:
print(r)
Output after Transpose Matrix
[6, 4, 3]
[7, 5, 8]
Comments