Home > Blockchain >  How to change diagonal elements in a matrix from 1 to 0, 0 to 1
How to change diagonal elements in a matrix from 1 to 0, 0 to 1

Time:10-06

Please can someone help with flipping elements on the diagonal of a matrix from 1 to 0 if 1, and 0 to 1 if 0 for the matrix rmat

mat = np.random.binomial(1,.5,4)
rmat = np.array([mat,]*4) 

Thank you

CodePudding user response:

You can use numpy.fill_diagonal.

NB. the operation is in place

diagonal = rmat.diagonal()
np.fill_diagonal(rmat, 1-diagonal)

input:

array([[1, 1, 1, 0],
       [1, 1, 1, 0],
       [1, 1, 1, 0],
       [1, 1, 1, 0]])

output:

array([[0, 1, 1, 0],
       [1, 0, 1, 0],
       [1, 1, 0, 0],
       [1, 1, 1, 1]])

CodePudding user response:

Try this -

Unlike the np.fill_diagonal, this method is not inplace and doesnt need explicit copy of the input rmat matrix.

n = rmat.shape[0]
output = np.where(np.eye(n, dtype=bool), np.logical_not(rmat), rmat)
output
#Original
[[0 1 0 0]
 [0 1 0 0]
 [0 1 0 0]
 [0 1 0 0]]

#diagonal inverted
[[1 1 0 0]
 [0 0 0 0]
 [0 1 1 0]
 [0 1 0 1]]

Another way to do this would be to use np.diag_indices along with np.logical_not

n = rmat.shape[0]
idx = np.diag_indices(n)

rmat[idx] = np.logical_not(rmat[idx])
print(rmat)
  • Related