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, 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