Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Numpy trace() Function



The Numpy trace() function is used to compute the sum of the diagonal elements of a 2D array or matrix, i.e., the sum of elements a[i, i+offset] for all i, where the offset determines which diagonal is selected (positive for diagonals above the main diagonal, and negative for diagonals below).

This function raises a ValueError if the input array is not 2D or if an unsupported offset is given.

Syntax

Following is the syntax of the Numpy trace() function −

numpy.trace(a, offset=0, axis1=0, axis2=1)  

Parameters

Following are the parameters of the Numpy trace() function −

  • a: The input 2D array or matrix.
  • offset (optional): The diagonal offset. A positive value shifts the diagonal above the main diagonal, and a negative value shifts it below. The default is 0, which represents the main diagonal.
  • axis1, axis2 (optional): The axes that define the 2D plane in the array from which the diagonal will be summed. By default, axis1=0 and axis2=1.

Return Type

This function returns the sum of the diagonal elements of the matrix.

Example

Following is a basic example of to calculate the sum of the main diagonal elements of a matrix using the Numpy trace() function −

import numpy as np  
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])  
result = np.trace(matrix)  
print("Sum of the main diagonal:", result)  

Output

Following is the output of the above code −

Sum of the main diagonal: 15

Example: Extracting Diagonal with an Offset

The offset parameter in the trace() function allows us to calculate the sum of the diagonal elements above or below the main diagonal. A positive value shifts the diagonal upwards (above the main diagonal), while a negative value shifts it downwards (below the main diagonal). Here, we have extracted and summed the elements above the main diagonal −

import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("Matrix:\n",matrix)
result = np.trace(matrix, offset=1)
print("Sum of the diagonal above the main diagonal:", result)

Output

Following is the output of the above code:

Matrix:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]
Sum of the diagonal above the main diagonal: 8 

Example: Diagonal Sum with Different Axes

We can specify different axes to compute the sum of the diagonal elements in non-square matrices. In the following example, we have used axes 0 and 1 to calculate the sum of the diagonal elements −

import numpy as np
matrix = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
print("Original Matrix:\n", matrix)
print("Shape of the Matrix:", matrix.shape)
result = np.trace(matrix, axis1=0, axis2=1)
print("Sum of diagonal with axes (0, 1):", result)

Output

Following is the output of the above code:

Original Matrix:
 [[1 2]
 [3 4]
 [5 6]
 [7 8]]
Shape of the Matrix: (4, 2)
Sum of diagonal with axes (0, 1): 6
numpy_array_manipulation.htm
Advertisements