0
0
NumpyHow-ToBeginner ยท 3 min read

How to Find Trace of Matrix Using NumPy

To find the trace of a matrix in NumPy, use the numpy.trace() function which sums the diagonal elements of the matrix. Pass your 2D array to numpy.trace() to get the trace value.
๐Ÿ“

Syntax

The syntax for finding the trace of a matrix using NumPy is:

  • numpy.trace(a, offset=0, axis1=-2, axis2=-1, dtype=None, out=None)

Here:

  • a is the input array (matrix).
  • offset shifts which diagonal to sum (0 is main diagonal).
  • axis1 and axis2 specify the axes to consider as the matrix dimensions.
  • dtype sets the data type for the output.
  • out is an optional output array to store the result.
python
numpy.trace(a, offset=0, axis1=-2, axis2=-1, dtype=None, out=None)
๐Ÿ’ป

Example

This example shows how to create a 3x3 matrix and find its trace using numpy.trace(). The trace is the sum of the diagonal elements.

python
import numpy as np

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

trace_value = np.trace(matrix)
print(trace_value)
Output
15
โš ๏ธ

Common Pitfalls

Common mistakes when finding the trace include:

  • Passing a 1D array instead of a 2D matrix, which will cause unexpected results.
  • Forgetting that offset changes which diagonal is summed (e.g., offset=1 sums the diagonal above the main diagonal).
  • Using non-square matrices without understanding that trace sums the diagonal elements present, which may be fewer than rows or columns.
python
import numpy as np

# Wrong: 1D array
arr_1d = np.array([1, 2, 3])
print(np.trace(arr_1d))  # Output is sum of elements, not a matrix trace

# Right: 2D array
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print(np.trace(arr_2d))  # Sums diagonal elements (1 + 5)
Output
6 6
๐Ÿ“Š

Quick Reference

Summary tips for using numpy.trace():

  • Use a 2D NumPy array as input.
  • Default offset=0 sums the main diagonal.
  • Use offset to sum diagonals above or below the main diagonal.
  • Works with non-square matrices by summing the overlapping diagonal elements.
โœ…

Key Takeaways

Use numpy.trace() to sum the diagonal elements of a matrix easily.
Pass a 2D NumPy array to get the correct trace value.
The offset parameter lets you choose which diagonal to sum.
Trace works on non-square matrices by summing the available diagonal elements.
Avoid passing 1D arrays to numpy.trace() as it may give unexpected results.