To do this in NumPy, without using a double loop, you can use tril_indices
. Note that depending on your matrix size, this may be slower that adding the transpose and subtracting the diagonal though perhaps this method is more readable.
>>> i_lower = np.tril_indices(n, -1)
>>> matrix[i_lower] = matrix.T[i_lower] # make the matrix symmetric
Be careful that you do not try to mix tril_indices
and triu_indices
as they both use row major indexing, i.e., this does not work:
>>> 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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…