Free cookie consent management tool by TermsFeed Finding the trace of a matrix using NumPy | Pythontic.com

Finding the trace of a matrix using NumPy

Overview:

  • The trace of a matrix is defined as the sum of the elements along with its main diagonal.

  • The trace of a matrix can be calculated for off-diagonals as well. The off-diagonals are diagonals above or below the main diagonal.

  • The NumPy function from the linalg module provides the trace() function that calculates and returns the trace for a given matrix for the specified diagonal. The off-diagonals are specified using an offset to the function trace().

Example:

# Example Python program that finds the trace of a matrix
# i.e., The sum of a specified diagonal
# using the numpy.linalg.trace()
import numpy

# Create a rectangular matrix of order 3x4
elems         = numpy.arange(-18, 17, 3)
rectMatrix  = elems.reshape(3, 4)
print("Rectangular matrix:")
print(rectMatrix)

# Sum along the main diagonal
trace = numpy.linalg.trace(rectMatrix) # offset = 0
print("Trace of the rectangular matrix along the main diagonal:")
print(trace)

# Sum of the off-diagonal whose offset is 1
trace = numpy.linalg.trace(rectMatrix, offset = 1)
print("Trace of the first off-diagonal above the main diagonal:")
print(trace)

# Sum of the off-diagonal whose offset is -1
trace = numpy.linalg.trace(rectMatrix, offset = -1)
print("Trace of the first off-diagonal below the main diagonal:")
print(trace)

Output:

Rectangular matrix:
[[-18 -15 -12  -9]
 [ -6  -3   0   3]
 [  6   9  12  15]]
Trace of the rectangular matrix along the main diagonal:
-9
Trace of the first off-diagonal above the main diagonal:
0
Trace of the first off-diagonal below the main diagonal:
3

 


Copyright 2025 © pythontic.com