Open In App

Python | Numpy matrix.transpose()

With the help of Numpy matrix.transpose() method, we can find the transpose of the matrix by using the matrix.transpose()method in Python.

Numpy matrix.transpose() Syntax

Syntax : matrix.transpose()



Parameter: No parameters; transposes the matrix it is called on.

Return : Return transposed matrix



What is Numpy matrix.transpose()?

`numpy.matrix.transpose()` is a function in the NumPy library that computes the transpose of a matrix. It swaps the rows and columns of the matrix, effectively reflecting it along its main diagonal. The function is called on a NumPy matrix object, and it does not take any parameters. The result is a new matrix representing the transposed version of the original matrix.

NumPy Matrix transpose() – Transpose of an Array in Python

There are numerous examples of `numpy.matrix.transpose()`. Here, we illustrate commonly used instances of `numpy.matrix.transpose()` for clarity.

NumPy Matrix Transformation

Example 1: In this example, the code uses the NumPy library to create a 2×3 matrix. It then calculates the transpose of the original matrix using the `transpose()` function. Finally, it prints both the original and transposed matrices to the console.




import numpy as np
 
# Original matrix
original_matrix = np.matrix([[1, 2, 3], [4, 5, 6]])
 
# Transposed matrix
transposed_matrix = original_matrix.transpose()
 
print("Original Matrix:")
print(original_matrix)
print("\nTransposed Matrix:")
print(transposed_matrix)

Output:

Original Matrix:
[[1 2 3]
 [4 5 6]]
Transposed Matrix:
[[1 4]
 [2 5]
 [3 6]]

Example 2: In this example This Python code uses the NumPy library to create a 3×3 matrix named ‘gfg’. It then applies the transpose() method to the matrix and assigns the result to ‘geek’. Finally, it prints the transposed matrix ‘geek’.




# import the important module in python
import numpy as np
               
# make matrix with numpy
gfg = np.matrix('[4, 1, 9; 12, 3, 1; 4, 5, 6]')
               
# applying matrix.transpose() method
geek = gfg.transpose()
     
print(geek)

Output:

[[ 4 12  4]
 [ 1  3  5]
 [ 9  1  6]]

Transpose of an Array Like Object

In this example code uses NumPy to create two 2×2 matrices, `matrix_a` and `matrix_b`. It then transposes `matrix_b` using the `transpose()` function and performs matrix multiplication between `matrix_a` and the transposed `matrix_b`. The result is printed to the console.




import numpy as np
 
# Matrices for multiplication
matrix_a = np.matrix([[1, 2], [3, 4]])
matrix_b = np.matrix([[5, 6], [7, 8]])
 
# Transpose one matrix before multiplication
result = matrix_a * matrix_b.transpose()
 
print("Result of Matrix Multiplication:")
print(result)

Output:

Result of Matrix Multiplication:
[[17 23]
 [39 53]]

Article Tags :