在不循环或调用np.diag()的情况下检索对角线元素的替代方法是什么



我有一个4x4数组A1,需要在不循环或调用np.diag((的情况下检索其对角线元素。有什么方法可以做到这一点?感谢你的帮助!

A1 = np.array([ [1, 4, 6, 8],[2, 5, 7, 10],[3, 6, 9, 13], [11, 12, 16, 0]])

通过使用对角线的索引进行索引,对角线的索引是单位矩阵的非零的索引。

import numpy as np
A1 = np.array([ [1, 4, 6, 8],[2, 5, 7, 10],[3, 6, 9, 13], [11, 12, 16, 0]])
diag_pos = np.eye(A1.shape[0],dtype=bool).nonzero()
print(A1[diag_pos])
[1 5 9 0]