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()`

, first`import 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:

: This represents the offset of the diagonal from the main diagonal. It can take a positive or negative value. The default value is`offset`

`0`

, which represents the main diagonal.: These represent the axes to be used as the first and second axis of the`axis1`

,`axis2`

`2-D`

sub-arrays from which the diagonals should be taken. The default values are the first two values of the`a`

parameter.: This represents the data type of the output array and the accumulator where the elements are summed.`dtype`

: This represents the array into which the output is placed.`out`

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)

**Line 1**: We import the`numpy`

library.**Line 4**: We create a 2D array`myarray`

of 9 elements with a dimension of`3 by 3`

, that is,`3`

rows and`3`

columns, using the`arange()`

function.**Line 7**: We implement the`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`

.**Line 9**: We print the array`myarray`

.**Line 10**: We print the new diagonal array`sumdiag`

.

Note: The output`12`

was obtained from the sum of the diagonal`0`

,`4`

, and`8`

.

TRENDING TOPICS