Transpose matrix implementation in python
Transpose means changing column into rows and rows into columns. It can be implemented in python with or without Numpy.
There are three methods to implement as follows.
- · Using Numpy
- · Using Zip
- · Manual Loops
Using Numpy:
Numpy is
predefined. It has many built-in functions.
Pyhon code:
import numpy as np1
# Step 1: create a 4X4 matrix
X = np1.array([[1, 2, 3, 6],
[4, 5, 6, 10],
[7, 8, 9, 2],
[3, 6, 4, 8]])
# Step 2: Transpose the matrix X
X_T = X.T
print("The Original Matrix:\n", X)
print("Here is the Transposed Matrix:\n", X_T)
Output:
The Original Matrix:
[[ 1 2 3 6]
[ 4 5 6 10]
[ 7 8 9 2]
[ 3 6 4 8]]
Here is the Transposed Matrix:
[[ 1 4 7 3]
[ 2 5 8 6]
[ 3 6 9 4]
[ 6 10 2 8]]
Using Zip:
Zip is
built-in function used for lists.
Python Code:
# Step 1: Let us create a 3X2 matrix
X = [[1, 2],
[4, 5],
[3, 6]]
# Step 2: Transpose the matrix using zip
X_T = list(map(list, zip(*X)))
print("Original Matrix is:\n", X)
print("Transposed Matrix is:\n", X_T)
Output:
Original Matrix is:
[[1, 2], [4, 5], [3, 6]]
Transposed Matrix is:
[[1, 4, 3], [2, 5, 6]]
Manual loops:
These are
created by the user.
Python Code:
# Step 1: Let us create a 3x2 matrix
X = [[1, 2],
[4, 3],
[5, 6]]
# Step 2: let rows and columns dimensions are assigned
m_rows = len(X)
m_cols = len(X[0])
# Step 3: An empty transpose matrix is createed
X_T = []
# Step 4: Fill it the values using nested loops
for c in range(m_cols):
new_row = []
for r in range(m_rows):
new_row.append(X[r][c])
X_T.append(new_row)
print("Original Matrix:\n", X)
print("Transposed Matrix:\n", X_T)
Output:
Original Matrix:
[[1, 2], [4, 3], [5, 6]]
Transposed Matrix:
[[1, 4, 5], [2, 3, 6]]
These are the three methods to implement transpose matrix in
python. Hope, you understood this. Keep coding!!!
Comments
Post a Comment