要在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