在python矩阵中将上三角复制到下三角

在python矩阵中将上三角复制到下三角,第1张

在python矩阵中将上三角复制到下三角

要在NumPy中执行此 *** 作,而无需使用双循环,可以使用

tril_indices
。请注意,根据矩阵的大小,这可能会比添加转置和减去对角线慢一些,尽管此方法可能更具可读性。

>>> i_lower = np.tril_indices(n, -1)>>> matrix[i_lower] = matrix.T[i_lower]  # make the matrix symmetric

注意不要混用

tril_indices
triu_indices
因为它们都使用行主索引,也就是说,这行不通:

>>> i_upper = np.triu_indices(n, 1)>>> i_lower = np.tril_indices(n, -1)>>> matrix[i_lower] = matrix[i_upper]  # make the matrix symmetric>>> np.allclose(matrix.T, matrix)False


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5649451.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存