The trace()
function in Python is simply used to return the sum along the diagonals of a given array.
numpy.trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None)
Note: To use
trace()
, firstimport numpy
.
The trace()
function takes a mandatory parameter value a
, which represents the array_like
object from which the diagonals are taken.
The trace()
function takes the following optional parameters:
offset
: This represents the offset of the diagonal from the main diagonal. It can take a positive or negative value. The default value is 0
, which represents the main diagonal.axis1
, axis2
: These represent the axes to be used as the first and second axis of the 2-D
sub-arrays from which the diagonals should be taken. The default values are the first two values of the a
parameter.dtype
: This represents the data type of the output array and the accumulator where the elements are summed.out
: This represents the array into which the output is placed.The trace()
function returns a sum along the diagonals of an array.
import numpy as np# creating an arraymyarray = np.arange(9).reshape((3,3))# implementing the diag() functionsumdiag = np.trace(myarray, dtype = float)print(myarray)print(sumdiag)
numpy
library.myarray
of 9 elements with a dimension of 3 by 3
, that is, 3
rows and 3
columns, using the arange()
function.trace()
function on the array myarray
using the default value of the parameters. myarray
will be passed as a float data type. The result is assigned to a new variable sumdiag
.myarray
.sumdiag
.Note: The output
12
was obtained from the sum of the diagonal0
,4
, and8
.