NumPy trace: Diagonals, Offsets, Axes, and Matrix Sums

Quick answer: np.trace sums a selected diagonal of an array. Use offset for diagonals above or below the main diagonal and axis1/axis2 for higher-dimensional inputs; use np.diagonal when the individual selected values must be inspected or transformed.

Python Pool infographic showing NumPy trace summing a matrix diagonal and selecting an offset diagonal from a rectangular array
np.trace sums elements along a diagonal; offset and axis parameters control which diagonal is used, including for higher-dimensional arrays.

numpy.trace() returns the sum along a diagonal. For a 2D array, that means the main diagonal by default. For a higher-dimensional array, it traces across two selected axes and keeps the remaining axes in the result.

The official NumPy documentation covers numpy.trace(), numpy.diagonal(), and numpy.diag().

Use trace() when you need the sum of diagonal entries. Use diagonal() when you need the diagonal values themselves before applying another calculation. Use diag() when you want to extract a diagonal from a 2D input or build a 2D diagonal array from a 1D input.

The default call is equivalent to summing the main diagonal across axes 0 and 1 for a 2D input. The offset parameter moves the diagonal above or below the main diagonal. A positive offset selects a diagonal above the main diagonal, while a negative offset selects one below it.

For arrays with more than two dimensions, axis1 and axis2 decide which two axes form the traced plane. NumPy sums the diagonal inside each plane and returns one result for each remaining coordinate.

The dtype parameter controls the accumulator and result dtype. It is useful when small integer input should be summed into a wider integer dtype, or when numeric precision needs to be made explicit.

The out parameter lets you provide an output array with the correct shape. It is less common in beginner code, but it can be useful in performance-sensitive routines that reuse storage.

A trace is not the same as a determinant. The trace sums diagonal elements. The determinant is a separate linear algebra operation with different meaning and different rules. Keeping the two terms separate prevents subtle mistakes in matrix code.

Also remember that np.trace() uses array axes, not row and column labels. If an array came from a table, confirm the shape and axis order before interpreting the result as a domain-specific total.

Compute The Main Diagonal Trace

The default call sums the main diagonal of a 2D array.

import numpy as np

matrix = np.array([
    [1, 2],
    [3, 4],
])

result = np.trace(matrix)

print(result)

The diagonal entries are 1 and 4.

The trace is their sum, so the output is 5.

This is the clearest form when the array is already shaped as rows and columns.

Use this style for small examples and tests because it makes the diagonal easy to inspect by eye.

Use Positive And Negative Offsets

The offset parameter selects a diagonal above or below the main diagonal.

import numpy as np

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

print(np.trace(matrix, offset=1))
print(np.trace(matrix, offset=-1))

offset=1 uses the diagonal just above the main diagonal.

offset=-1 uses the diagonal just below the main diagonal.

Offsets are useful when neighboring diagonals carry meaning, such as transition counts or banded matrix values.

If the selected diagonal is shorter than the main diagonal, NumPy sums only the elements on that selected diagonal.

Python Pool infographic showing a matrix diagonal, trace sum, and NumPy trace
Main diagonal: A matrix diagonal, trace sum, and NumPy trace.

Choose A Safer dtype

Use dtype when the accumulation dtype should be explicit.

import numpy as np

matrix = np.array([
    [100, 200],
    [300, 400],
], dtype=np.int16)

result = np.trace(matrix, dtype=np.int64)

print(result)
print(result.dtype)

The input is a small integer dtype.

The trace is accumulated and returned as int64.

This avoids relying on dtype promotion rules when a larger total might be possible in real data.

For floating-point data, make dtype choices just as explicit when precision or downstream storage matters.

Compare trace() With diagonal()

diagonal() returns the diagonal values, while trace() returns their sum.

import numpy as np

matrix = np.array([
    [2, 4, 6],
    [8, 10, 12],
    [14, 16, 18],
])

diagonal = np.diagonal(matrix)
result = np.trace(matrix)

print(diagonal)
print(result)

The diagonal values are available as an array.

The trace is the sum of those values.

Use diagonal() first when you need to inspect, filter, or transform diagonal values before summing them.

Use trace() directly when the final answer should be a diagonal sum.

Trace Across Selected Axes

For a 3D array, choose the two axes that form each traced plane.

import numpy as np

data = np.arange(18).reshape(2, 3, 3)

result = np.trace(data, axis1=1, axis2=2)

print(result)

Here each item along axis 0 contains a 3 by 3 plane.

NumPy traces each plane and returns one result per item along axis 0.

This pattern is common when you have a stack of matrices and need one trace per matrix.

When axis order is not obvious, print the input shape and a small slice before using the result in a larger calculation.

Python Pool infographic comparing positive offset, main diagonal, negative offset, and sums
Diagonal offset: Positive offset, main diagonal, negative offset, and sums.

Write The Result Into out

The out parameter stores the result in an existing output array.

import numpy as np

matrix = np.array([
    [1.5, 2.5],
    [3.5, 4.5],
])

out = np.empty((), dtype=float)
np.trace(matrix, out=out)

print(out)

A 2D trace returns a scalar-shaped result, so the output array is scalar-shaped too.

For higher-dimensional input, the output shape must match the remaining axes after the trace is computed.

Use out only when the storage reuse is intentional and the shape is clear.

In short, use np.trace() for diagonal sums, set offset when a neighboring diagonal matters, choose axis1 and axis2 deliberately for higher-dimensional arrays, and make dtype or output storage explicit when correctness depends on it.

Select The Main Diagonal

For a two-dimensional matrix, offset zero selects entries whose row and column indices match. The matrix does not need to be square; the diagonal stops at the first dimension boundary.

Python Pool infographic mapping axis1, axis2, batches, and trace output for multidimensional arrays
Matrix axes: Axis1, axis2, batches, and trace output for multidimensional arrays.

Use Positive And Negative Offsets

A positive offset selects a diagonal above the main diagonal and a negative offset selects one below it. Validate that the selected diagonal is meaningful for the input shape.

Handle Higher Dimensions

For arrays with more than two dimensions, axis1 and axis2 identify the pair of axes used for the diagonal while the other axes remain in the result. Write down the intended shape before calling trace.

Choose The Result Dtype

The dtype parameter can control accumulation and output representation. Consider integer overflow, floating-point precision, complex sums, and object arrays before relying on defaults.

Python Pool infographic testing rectangular matrices, dtype, offsets, and shape validation
Trace checks: Rectangular matrices, dtype, offsets, and shape validation.

Compare With diagonal

np.diagonal returns a view or read-only view depending on context and version details, while trace performs the reduction. Use diagonal for per-entry validation and trace for the aggregate.

Test Offset And Axis Cases

Test square and rectangular arrays, positive and negative offsets, invalid axes, singleton dimensions, complex values, dtype behavior, and a hand-computed result for each supported shape.

Use the official NumPy trace documentation for offsets, axes, and dtype behavior. Related Python Pool references include NumPy arrays and tests.

For related array reductions, compare NumPy array axes, diagonal tests, and sequence inspection before summing a trace.

Frequently Asked Questions

What does NumPy trace return?

np.trace returns the sum of elements along a diagonal of an array, with offset and axis parameters controlling the selected diagonal.

How do I sum an off-diagonal in NumPy?

Pass an offset to trace; positive and negative offsets select diagonals above or below the main diagonal according to the chosen axes.

Can np.trace work on a rectangular matrix?

Yes. The diagonal length depends on the shape and offset, so a rectangular matrix can have a shorter selected diagonal.

What is the difference between trace and diagonal?

diagonal returns the selected diagonal values, while trace sums them; use diagonal when you need to inspect, transform, or validate individual entries.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted