To transpose a matrix with NumPy, call the transpose() method.
For instance:
import numpy as np A = np.array([[1, 2], [3, 4]]) A_T = A.transpose() print(A_T)
Output:
[[1 3] [2 4]]
If you are in a hurry, I’m sure this quick answer is enough.
To learn more about matrix transpose, keep on reading.
What Is the Transpose of a Matrix
The transpose of a matrix is another matrix where the matrix is flipped along its diagonal axis. This means each row of the matrix turns into a column in the result matrix.
Transpose is a really common operation performed on a matrix.
Here is an illustration of a transpose of a 3 x 3 matrix.
Notice that the matrix does not need to be a square matrix (such as a 3 x 3) to be transposed. You can just as well transpose a 2 x 4 matrix or a 5 x 2 matrix.
Next, let’s implement a matrix transpose algorithm with Python.
Matrix Transpose Algorithm
Transposing a matrix is easy to describe for someone with paper and pen.
Turn each row into a column.
However, when giving instructions to a computer, it is not that easy.
A computer program that transposes a matrix needs to loop through the matrix row by row, pick each element, and put it into a slot in the result array.
The general description of a matrix transpose algorithm as pseudocode is as follows:
- Specify a 2D array A[M][N], that represents a M x N matrix.
- Declare another 2D array T to store the result of the transpose with dimensions N x M (reversed compared to the original array.)
- Loop through the original 2D array and convert its rows to the columns of matrix T.
- Declare 2 variables i and j.
- Set i, j = 0
- Repeat until i < M
- Set j = 0
- Repeat until j < N
- T[i][j] = A[j][i]
- j = j + 1
- i = i + 1
- Show the result matrix T.
With this information, let’s implement the matrix transpose algorithm in Python.
# Declare the matrix A = [ [9, 7], [4, 5], [3, 8] ] # Set up the result matrix T = [ [0, 0, 0], [0, 0, 0] ] # Know the dimensions in A M = len(A[0]) N = len(A) # Loop through A i = 0 while i < M: j = 0 while j < N: # Transpose each element T[i][j] = A[j][i] j = j + 1 i = i + 1 # Show the result for row in T: print(row)
Output:
[9, 4, 3] [7, 5, 8]
Now that you understand what is a matrix transpose and how to create a Python program to find one, let’s see how to do it more easily.
How to Transpose a Matrix with NumPy
In NumPy, matrices are commonly expressed as 2D arrays, where each inner array represents one row of the matrix.
However, transposing a matrix is such a common operation, that a NumPy array has a built-in function for it.
This function is called the numpy.matrix.transpose.
It can be called on a NumPy array.
For instance, let’s transpose a 2 x 3 matrix:
import numpy as np A = np.array( [ [9, 7], [4, 5], [3, 8] ] ) T = A.transpose() print(T)
Output:
[[9 4 3] [7 5 8]]
Conclusion
Today you learned how to transpose a matrix in Python by:
- Implementing your own matrix transpose algorithm
- Using a built-in transpose function in the NumPy library.