1

I have a sparse matrix below.

a = sparse.diags([1,2,3],[-1,0,1],shape=(6,6),format ="csr")

I want to take the reciprocal of each of the elements in the sparse matrix. I search it on the internet and notice that taking the reciprocal is barely mentioned. I know numpy has a reciprocal function. np.reciprocal() But it does not work in my case.

It does not have to have such a recipical function. If somebody can provide an elementwise division function of two sparse matrices of same size, or elementwise power function(power of -1), that will also be great.
Thank you So much.

Guangyue He
  • 269
  • 1
  • 3
  • 14

1 Answers1

1

If you only want to take the reciprocal of the nonzero elements, you can use

M.nonzero() = 1 / M.nonzero()

It depends on which sparsity form you are using whether this will be fast or not!

Or borrowing from Efficient way of taking Logarithm function in a sparse matrix, you can use

new_data = 1/M.data
M = csr_matrix((new_data, (M.row, M.col)), shape = M.shape)

Or (late edit, thanks to joeln), the above can be done in place with

np.reciprocal(M.data, out=M.data)

and then the entries of M will be inverted.

Community
  • 1
  • 1
colcarroll
  • 3,632
  • 17
  • 25
  • You can't assign to `M.nonzero()`. The next option will work, but the operation can be performed in-place with, `np.reciprocal(M.data, out=M.data)`. – joeln Mar 05 '14 at 02:26