numpy.linalg.trace#

linalg.trace(x,/,*,offset=0,dtype=None)[source]#

Returns the sum along the specified diagonals of a matrix(or a stack of matrices)x.

This function is Array API compatible, contrary tonumpy.trace.

Parameters:
x(…,M,N) array_like

Input array having shape (…, M, N) and whose innermost twodimensions form MxN matrices.

offsetint, optional

Offset specifying the off-diagonal relative to the main diagonal,where:

*offset=0:themaindiagonal.*offset>0:off-diagonalabovethemaindiagonal.*offset<0:off-diagonalbelowthemaindiagonal.
dtypedtype, optional

Data type of the returned array.

Returns:
outndarray

An array containing the traces and whose shape is determined byremoving the last two dimensions and storing the traces in the lastarray dimension. For example, if x has rank k and shape:(I, J, K, …, L, M, N), then an output array has rank k-2 and shape:(I, J, K, …, L) where:

out[i,j,k,...,l]=trace(a[i,j,k,...,l,:,:])

The returned array must have a data type as described by the dtypeparameter above.

See also

numpy.trace

Examples

>>>np.linalg.trace(np.eye(3))3.0>>>a=np.arange(8).reshape((2,2,2))>>>np.linalg.trace(a)array([3, 11])

Trace is computed with the last two axes as the 2-d sub-arrays.This behavior differs fromnumpy.trace which uses the first twoaxes by default.

>>>a=np.arange(24).reshape((3,2,2,2))>>>np.linalg.trace(a).shape(3, 2)

Traces adjacent to the main diagonal can be obtained by using theoffset argument:

>>>a=np.arange(9).reshape((3,3));aarray([[0, 1, 2],       [3, 4, 5],       [6, 7, 8]])>>>np.linalg.trace(a,offset=1)# First superdiagonal6>>>np.linalg.trace(a,offset=2)# Second superdiagonal2>>>np.linalg.trace(a,offset=-1)# First subdiagonal10>>>np.linalg.trace(a,offset=-2)# Second subdiagonal6
On this page