numpy.linalg.trace#
- linalg.trace(x, /, *, offset=0, dtype=None)[原始碼]#
傳回矩陣(或矩陣堆疊)
x
沿指定對角線的總和。此函數與 Array API 相容,與
numpy.trace
相反。- 參數:
- x(…,M,N) 類陣列
輸入陣列的形狀為 (…, M, N),且最內層的兩個維度構成 MxN 矩陣。
- offsetint,選填
指定相對於主對角線的偏移對角線的偏移量,其中
* 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 維子陣列計算的。此行為與
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