NumPy ndarray.trace()
The numpy.ndarray.trace()
method computes the sum of the diagonal elements of a NumPy array.
It allows specifying an offset to shift the diagonal, as well as the axes to extract the diagonal from.
Syntax
ndarray.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
Parameters
Parameter | Type | Description |
---|---|---|
offset | int, optional | Specifies which diagonal to sum. Default is 0 (main diagonal). Positive values move the diagonal above, negative values below. |
axis1 | int, optional | The first axis of the 2D sub-array from which the diagonal is taken. Default is 0 . |
axis2 | int, optional | The second axis of the 2D sub-array from which the diagonal is taken. Default is 1 . |
dtype | dtype, optional | Data type to use for summation. If None , it uses the array’s data type. |
out | ndarray, optional | Alternative output array to store the result. Must match expected output shape. |
Return Value
Returns a scalar value representing the sum of the specified diagonal elements.
Examples
1. Computing the Trace of a Square Matrix
In this example, we compute the trace of a 3×3 matrix, which is the sum of its main diagonal elements.
import numpy as np
# Define a 3x3 matrix
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# Compute the trace (sum of main diagonal elements: 1 + 5 + 9)
result = arr.trace()
print("Trace of the matrix:", result)
Output:
Trace of the matrix: 15
2. Using the offset
Parameter
The offset
parameter shifts the diagonal from which the sum is computed.
A positive value selects diagonals above the main diagonal, while a negative value selects below.
import numpy as np
# Define a 4x4 matrix
arr = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]])
# Compute the trace of the diagonal above the main diagonal (offset=1)
result_offset1 = arr.trace(offset=1)
# Compute the trace of the diagonal below the main diagonal (offset=-1)
result_offset_neg1 = arr.trace(offset=-1)
print("Trace with offset=1:", result_offset1) # 2 + 7 + 12 = 21
print("Trace with offset=-1:", result_offset_neg1) # 5 + 10 + 15 = 30
Output:
Trace with offset=1: 21
Trace with offset=-1: 30
3. Specifying Custom Axes for the Diagonal
The axis1
and axis2
parameters allow computing the trace along different axes in multi-dimensional arrays.
import numpy as np
# Define a 3D array (2x3x3)
arr = np.array([[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],
[[10, 11, 12],
[13, 14, 15],
[16, 17, 18]]])
# Compute the trace along the specified axes (axis1=1, axis2=2)
result = arr.trace(axis1=1, axis2=2)
print("Trace along custom axes:\n", result)
Output:
[15 42]
Here, the function extracts the diagonal from each 3×3 sub-array and sums them, returning one value per 2D slice.
4. Changing Data Type with dtype
By using the dtype
parameter, we can specify the precision used for summation.
import numpy as np
# Define a float matrix
arr = np.array([[1.1, 2.2, 3.3],
[4.4, 5.5, 6.6],
[7.7, 8.8, 9.9]])
# Compute trace with integer dtype
result = arr.trace(dtype=int)
print("Trace with integer dtype:", result)
Output:
Trace with integer dtype: 15
Here, the floating-point values are cast to integers before summation, truncating the decimal part.