numpy.linalg.trace#
- linalg.trace(x, /, *, offset=0, dtype=None)[源代码]#
返回矩阵(或矩阵堆栈)
x指定对角线上的总和.此函数与 Array API 兼容,与
numpy.trace相反.- 参数:
- x(…,M,N) array_like
输入数组,其形状为 (…, M, N),并且最里面的两个维度形成 MxN 矩阵.
- offset整数,可选
偏移量,指定相对于主对角线的非对角线,其中:
* offset = 0: the main diagonal. * offset > 0: off-diagonal above the main diagonal. * offset < 0: off-diagonal below the main diagonal.
- dtypedtype, optional
返回数组的数据类型.
- 返回:
- 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