numpy.linalg.trace#
- linalg.trace(x, /, *, offset=0, dtype=None)[源代码]#
返回矩阵(或矩阵堆栈)
x的指定对角线上的总和.与
numpy.trace相比,此函数与 Array API 兼容.- 参数:
- x(…,M,N) array_like
具有形状 (…, M, N) 的输入数组,其最里面的两个维度形成 MxN 矩阵.
- offsetint, optional
指定相对于主对角线的非对角线的偏移量,其中:
* offset = 0: the main diagonal. * offset > 0: off-diagonal above the main diagonal. * offset < 0: off-diagonal below the main diagonal.
- dtypedtype,可选
返回数组的数据类型.
- 返回:
- outndarray
一个包含迹的数组,其形状由删除最后两个维度并将迹存储在最后一个数组维度中来确定. 例如,如果 x 的秩为 k 且形状为:(I, J, K, …, L, M, N),则输出数组的秩为 k-2 且形状为:(I, J, K, …, L),其中:
out[i, j, k, ..., l] = trace(a[i, j, k, ..., l, :, :])
返回的数组必须具有上述 dtype 参数描述的数据类型.
参见
示例
>>> np.linalg.trace(np.eye(3)) 3.0 >>> a = np.arange(8).reshape((2, 2, 2)) >>> np.linalg.trace(a) array([3, 11])
迹是使用最后两个轴作为 2-d 子数组计算的. 此行为与默认使用前两个轴的
numpy.trace不同.>>> a = np.arange(24).reshape((3, 2, 2, 2)) >>> np.linalg.trace(a).shape (3, 2)
可以使用 offset 参数获得与主对角线相邻的迹:
>>> a = np.arange(9).reshape((3, 3)); a array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> np.linalg.trace(a, offset=1) # First superdiagonal 6 >>> np.linalg.trace(a, offset=2) # Second superdiagonal 2 >>> np.linalg.trace(a, offset=-1) # First subdiagonal 10 >>> np.linalg.trace(a, offset=-2) # Second subdiagonal 6