MCPcopy Create free account
hub / github.com/numpy/numpy / trace

Function trace

numpy/core/fromnumeric.py:1701–1761  ·  view source on GitHub ↗

Return the sum along diagonals of the array. If `a` is 2-D, the sum along its diagonal with the given offset is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i. If `a` has more than two dimensions, then the axes specified by axis1 and axis2 are used to determin

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

Source from the content-addressed store, hash-verified

1699
1700@array_function_dispatch(_trace_dispatcher)
1701def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
1702 """
1703 Return the sum along diagonals of the array.
1704
1705 If `a` is 2-D, the sum along its diagonal with the given offset
1706 is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i.
1707
1708 If `a` has more than two dimensions, then the axes specified by axis1 and
1709 axis2 are used to determine the 2-D sub-arrays whose traces are returned.
1710 The shape of the resulting array is the same as that of `a` with `axis1`
1711 and `axis2` removed.
1712
1713 Parameters
1714 ----------
1715 a : array_like
1716 Input array, from which the diagonals are taken.
1717 offset : int, optional
1718 Offset of the diagonal from the main diagonal. Can be both positive
1719 and negative. Defaults to 0.
1720 axis1, axis2 : int, optional
1721 Axes to be used as the first and second axis of the 2-D sub-arrays
1722 from which the diagonals should be taken. Defaults are the first two
1723 axes of `a`.
1724 dtype : dtype, optional
1725 Determines the data-type of the returned array and of the accumulator
1726 where the elements are summed. If dtype has the value None and `a` is
1727 of integer type of precision less than the default integer
1728 precision, then the default integer precision is used. Otherwise,
1729 the precision is the same as that of `a`.
1730 out : ndarray, optional
1731 Array into which the output is placed. Its type is preserved and
1732 it must be of the right shape to hold the output.
1733
1734 Returns
1735 -------
1736 sum_along_diagonals : ndarray
1737 If `a` is 2-D, the sum along the diagonal is returned. If `a` has
1738 larger dimensions, then an array of sums along diagonals is returned.
1739
1740 See Also
1741 --------
1742 diag, diagonal, diagflat
1743
1744 Examples
1745 --------
1746 >>> np.trace(np.eye(3))
1747 3.0
1748 >>> a = np.arange(8).reshape((2,2,2))
1749 >>> np.trace(a)
1750 array([6, 8])
1751
1752 >>> a = np.arange(24).reshape((2,2,2,3))
1753 >>> np.trace(a).shape
1754 (2, 3)
1755
1756 """
1757 if isinstance(a, np.matrix):
1758 # Get trace of matrix via an array to preserve backward compatibility.

Callers

nothing calls this directly

Calls 3

asanyarrayFunction · 0.85
traceMethod · 0.80
asarrayFunction · 0.70

Tested by

no test coverage detected