numpy.trace

numpy.trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None)

Return the sum along diagonals of the array.

If a is 2-d, returns the sum along the diagonal of self with the given offset, i.e., the collection of elements of the form a[i,i+offset]. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-d subarray whose trace is returned. The shape of the resulting array can be determined by removing axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals.

Parameters:

a : array_like

Array from whis the diagonals are taken.

offset : integer, optional

Offset of the diagonal from the main diagonal. Can be both positive and negative. Defaults to main diagonal.

axis1 : integer, optional

Axis to be used as the first axis of the 2-d subarrays from which the diagonals should be taken. Defaults to first axis.

axis2 : integer, optional

Axis to be used as the second axis of the 2-d subarrays from which the diagonals should be taken. Defaults to second axis.

dtype : dtype, optional

Determines the type of the returned array and of the accumulator where the elements are summed. If dtype has the value None and a is of integer type of precision less than the default integer precision, then the default integer precision is used. Otherwise, the precision is the same as that of a.

out : array, optional

Array into which the sum can be placed. Its type is preserved and it must be of the right shape to hold the output.

Returns:

sum_along_diagonals : ndarray

If a is 2-d, a 0-d array containing the diagonal is returned. If a has larger dimensions, then an array of diagonals is returned.

Examples

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

Previous topic

numpy.linalg.det

Next topic

numpy.linalg.solve

This Page

Quick search