📜  Python| numpy matrix.trace()(1)

📅  最后修改于: 2023-12-03 15:19:13.906000             🧑  作者: Mango

Python | numpy matrix.trace()

The numpy matrix.trace() function in Python returns the sum along the main diagonal of a matrix. The main diagonal of a matrix is a collection of elements where the row and column indices are the same. This function is particularly useful for calculating the trace of a matrix.

Syntax
numpy.matrix.trace()
Parameters

This function does not take any parameters.

Return Value

The numpy matrix.trace() function returns the sum of all the elements along the main diagonal of the matrix.

Example

Consider the following example:

import numpy as np

# Create a matrix
matrix = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Calculate the trace
trace = matrix.trace()

print("Matrix:")
print(matrix)
print("\nTrace:")
print(trace)

Output:

Matrix:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Trace:
15

In the above example, we create a matrix using the numpy.matrix() function. We then calculate the trace of the matrix using the trace() function. The output shows the original matrix and the trace value 15.

Further Reading
  • numpy.diag() - Learn about the function to extract the main diagonal from a matrix.
  • numpy.matrix() - Find more details about creating matrices in NumPy.