您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

要在NumPy中执行此操作,而无需使用双循环,可以使用tril_indices。请注意,根据矩阵的大小,这可能会比添加转置和减去对角线慢一些,尽管此方法可能更具可读性。

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

注意不要混用tril_indicestriu_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
python 2022/1/1 18:25:31 有643人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶