MCPcopy Index your code
hub / github.com/numpy/numpy / trace

Function trace

numpy/_core/fromnumeric.py:1845–1910  ·  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

1843
1844@array_function_dispatch(_trace_dispatcher)
1845def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
1846 """
1847 Return the sum along diagonals of the array.
1848
1849 If `a` is 2-D, the sum along its diagonal with the given offset
1850 is returned, i.e., the sum of elements ``a[i,i+offset]`` for all i.
1851
1852 If `a` has more than two dimensions, then the axes specified by axis1 and
1853 axis2 are used to determine the 2-D sub-arrays whose traces are returned.
1854 The shape of the resulting array is the same as that of `a` with `axis1`
1855 and `axis2` removed.
1856
1857 Parameters
1858 ----------
1859 a : array_like
1860 Input array, from which the diagonals are taken.
1861 offset : int, optional
1862 Offset of the diagonal from the main diagonal. Can be both positive
1863 and negative. Defaults to 0.
1864 axis1, axis2 : int, optional
1865 Axes to be used as the first and second axis of the 2-D sub-arrays
1866 from which the diagonals should be taken. Defaults are the first two
1867 axes of `a`.
1868 dtype : dtype, optional
1869 Determines the data-type of the returned array and of the accumulator
1870 where the elements are summed. If dtype has the value None and `a` is
1871 of integer type of precision less than the default integer
1872 precision, then the default integer precision is used. Otherwise,
1873 the precision is the same as that of `a`.
1874 out : ndarray, optional
1875 Array into which the output is placed. Its type is preserved and
1876 it must be of the right shape to hold the output.
1877
1878 Returns
1879 -------
1880 sum_along_diagonals : ndarray
1881 If `a` is 2-D, the sum along the diagonal is returned. If `a` has
1882 larger dimensions, then an array of sums along diagonals is returned.
1883
1884 See Also
1885 --------
1886 diag, diagonal, diagflat
1887
1888 Examples
1889 --------
1890 >>> import numpy as np
1891 >>> np.trace(np.eye(3))
1892 3.0
1893 >>> a = np.arange(8).reshape((2,2,2))
1894 >>> np.trace(a)
1895 array([6, 8])
1896
1897 >>> a = np.arange(24).reshape((2,2,2,3))
1898 >>> np.trace(a).shape
1899 (2, 3)
1900
1901 """
1902 if isinstance(a, np.matrix):

Callers

nothing calls this directly

Calls 3

asanyarrayFunction · 0.85
traceMethod · 0.80
asarrayFunction · 0.70

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…