Search code examples
pythonnumpyscipysparse-matrixsqrt

sqrt for element-wise sparse matrix


I have a sparse matrix:

from scipy import sparse
a = sparse.diags([1,4,9],[-1,0,1],shape =(10,10),format ="csr")

I want to take the square root of each of the elements in the sparse matrix I look up on the internet and it says I can use numpy.sqrt() to implement this. But error occurs:

  b = numpy.sqrt(a)
  AttributeError: sqrt

How can I do it?


Solution

  • Caveat, this will create a resulting numpy ndarray instead of a sparse csr array.

    from scipy import sparse
    a = sparse.diags([1,4,9],[-1,0,1],shape =(10,10),format ="csr")
    
    numpy.sqrt(a.data)
    

    As far as I can tell most of the other ufunc operations (sin, cos, ... ) do have sparse ufuncs except for sqrt, don't know the reason why. See this issue: https://github.com/scipy/scipy/pull/208