pythonnumpymatrixmultidimensional-arraydiagonal

Python: Non diagonal elements of a matrix to 0


What is the quickest way to convert the non-diagonal elements of a square symmetrical numpy ndarray to 0?


Solution

  • I'd check out the speed of saving the diagonal away, then zap the matrix, then restore the diagonal:

    n = len(mat)
    d = mat.ravel()[::n+1]
    values = d.copy()
    mat[:,:] = 0
    d[:] = values
    

    if the matrix is not huge may be however that just allocating a new one is faster

    mat = numpy.diag(numpy.diag(mat))