Skip to content

pymath.trace

fabian-flassig edited this page Jul 8, 2026 · 2 revisions

Returns the trace of a square tensor: the sum of its diagonal elements.

This function is located in the pymath module. See pymath for the matrix and tensor representation.

t = pymath.trace(A)
Parameter Type Description
A tensor A tensor that is square in every dimension (e.g. an n × n matrix). For a rank-r tensor the diagonal runs over the entries A[k][k]…[k].

Return value

Type Description
t The sum of the diagonal elements as a number.

Notes:

  • A must be square in all of its dimensions, otherwise an error is raised.
  • Only the diagonal entries are read; the rest of the tensor is never accessed. Missing entries read as 0.
  • The diagonal is summed with high numerical accuracy, even for large tensors.

Example:

local A = {{1, 2, 3},
           {4, 5, 6},
           {7, 8, 9}}
local t = pymath.trace(A)
-- t == 15        -- 1 + 5 + 9

Version Support:

Minimum PYTHA Version: V27

See also:

pymath, pymath.determinant, pymath.dot

Clone this wiki locally