numpy.linalg.trace#
- linalg.trace(x, /, *, offset=0, dtype=None)[source]#
返回矩阵(或矩阵栈)
x
指定对角线上的和。此函数兼容数组 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.
- dtype数据类型, 可选
dtype数据类型,可选
- 返回数组的数据类型。
- 返回:
outndarray 类型
out[i, j, k, ..., l] = trace(a[i, j, k, ..., l, :, :])
一个包含迹的数组,其形状通过移除最后两个维度并将迹存储在数组的最后一个维度中来确定。例如,如果 x 的秩为 k 且形状为:(I, J, K, …, L, M, N),则输出数组的秩为 k-2 且形状为:(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])
在浏览器中尝试!
>>> a = np.arange(24).reshape((3, 2, 2, 2)) >>> np.linalg.trace(a).shape (3, 2)
迹是根据最后两个轴作为二维子数组计算的。此行为与默认使用前两个轴的
numpy.trace
不同。>>> 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