2

Given a scipy.sparse.csr.csr_matrix, is there a quick way to return the elements on the diagonal?

The reason I would like to do this is to compute inv(D) A, where D is a diagonal matrix whose diagonal entries agree with A (A is my sparse matrix, guaranteed to have nonzeros on the diagonal).

gsamaras
  • 71,951
  • 46
  • 188
  • 305

1 Answers1

2

Use csr_matrix.diagonal():

Returns the main diagonal of the matrix

Example:

>>> import numpy as np
>>> from scipy.sparse import csr_matrix
>>> mymat = csr_matrix((4, 4), dtype=np.int8)
>>> mymat.diagonal()
array([0, 0, 0, 0], dtype=int8)
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • 2
    *sigh*. When you fail completely at googling :-) Thank you for the answer! +1 (will accept after the 10 minute lockout) –  Aug 21 '16 at 21:06
  • 1
    In your example `mymat` is a dense array (that `toarray()` :) ). The sparse diagonal isn't quite a general as the dense one. – hpaulj Aug 21 '16 at 21:43
  • @hpaulj thanks for the suggestion. I updated the post with Warren's suggestion. Hope you both guys will like my answer now! :) By the way, I got driven by the ref, but what you say makes sense. – gsamaras Aug 22 '16 at 01:49