Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
NumPy trace()
In this tutorial, you will learn about the numpy.trace() method with the help of examples.
The numpy.trace() function is used to return the sum of the diagonals of the matrix.
Example
import numpy as np
# create a 2D matrix
matrix = np.array([[1, 2],
[4, 6]])
# calculate the trace of the matrix
result = np.trace(matrix)
print(result)
# Output: 7
trace() Syntax
The syntax of trace() is:
numpy.trace(matrix, offset=0, dtype=None, out=None)
trace() Arguments
The trace() method takes the following arguments:
matrix- the input matrix from which the diagonals are takenoffset(optional) - offset of the diagonal from the main diagonaldtype(optional) - determines the data-type of the returned matrix
trace() Return Value
The trace() method returns the sum of the diagonals of matrix.
Example 1: Calculate Trace of a Matrix
import numpy as np
# create a matrix
matrix1 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# calculate the trace of the matrix and return integer value
result = np.trace(matrix1, dtype=int)
print(result)
Output
15
In the above example, the trace of the matrix is the sum of the elements on the diagonal of matrix1 (i.e., 1 + 5 + 9 = 15).
Example 2: Use of offset Argument in trace()
import numpy as np
# create a matrix
matrix1 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# calculate trace of the matrix with offset 1
result1 = np.trace(matrix1, offset=1)
print("With offset=1:", result1) # Output: 8 (2 + 6)
# calculate trace of the matrix with offset -1
result2 = np.trace(matrix1, offset=-1)
print("With offset=-1:", result2) # Output: 12 (4 + 8)
Output
With offset=1: 8 With offset=-1: 12
Here,
- If you set the offset to a positive integer, the function will compute the sum of a diagonal above the main diagonal.
- If you set the offset to a negative integer, the function will compute the sum of a diagonal below the main diagonal.