要在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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)