For a square matrix, the trace is simply the sum of the elements where the row index equals the column index — the same diagonal that np.eye() fills with ones. For a non-square matrix, trace() still works, summing along the diagonal up to the shorter dimension. The offset parameter lets you sum a diagonal above (positive offset) or below (negative offset) the main one instead. The trace is a useful summary statistic in linear algebra — for example, it equals the sum of a matrix's eigenvalues, a fact used in various numerical algorithms.
1Understanding np.trace()
For a square matrix, the trace is simply the sum of the elements where the row index equals the column index — the same diagonal that np.eye() fills with ones. For a non-square matrix, trace() still works, summing along the diagonal up to the shorter dimension. The offset parameter lets you sum a diagonal above (positive offset) or below (negative offset) the main one instead. The trace is a useful summary statistic in linear algebra — for example, it equals the sum of a matrix's eigenvalues, a fact used in various numerical algorithms.
The trace equals the sum of a matrix's eigenvalues — a useful mental shortcut and sanity check when working with eigenvalue-related computations, since you can verify np.trace(A) roughly matches the sum of np.linalg.eigvals(A).
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(np.trace(matrix))2Practical Example
Here is a real-world application of np.trace() showing how it is used in production NumPy code.
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(np.trace(matrix, offset=1))3Best Practices
Follow these guidelines when working with np.trace():
1. Use np.trace() directly instead of manually extracting the diagonal with np.diagonal() and summing it, for clarity
2. Use the offset parameter when you specifically need a diagonal other than the main one, rather than manually indexing
3. Remember trace() works on non-square matrices too, summing only up to the length of the shorter dimension
Tip: The trace equals the sum of a matrix's eigenvalues — a useful mental shortcut and sanity check when working with eigenvalue-related computations, since you can verify np.trace(A) roughly matches the sum of np.linalg.eigvals(A).
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(np.trace(matrix))