fn

trace

Tensor
trace(input: Tensor)
source

Return the sum of the diagonal entries of a 2-D tensor.

For a matrix ARn×nA \in \mathbb{R}^{n \times n} (or its non-square generalisation, where the shorter dimension determines the diagonal length), trace reduces along the main diagonal.

Parameters

inputTensor
2-D tensor. Non-square matrices use the shorter axis for the diagonal length.

Returns

Tensor

0-D tensor (scalar).

Notes

tr(A)  =  i=1min(m,n)Aii.\mathrm{tr}(A) \;=\; \sum_{i=1}^{\min(m,n)} A_{ii} .

The trace is invariant under cyclic permutations of products: tr(AB)=tr(BA)\mathrm{tr}(AB) = \mathrm{tr}(BA).

Examples

>>> import lucid
>>> A = lucid.tensor([[1.0, 2.0], [3.0, 4.0]])
>>> lucid.trace(A)
Tensor(5.)