par par - 1 year ago 126
Python Question

Return diagonal elements of scipy sparse matrix

Given a

, 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
is a diagonal matrix whose diagonal entries agree with
is my sparse matrix, guaranteed to have nonzeros on the diagonal).

Answer Source

Use csr_matrix.diagonal():

Returns the main diagonal of the matrix


>>> import numpy as np
>>> from scipy.sparse import csr_matrix
>>> mymat = csr_matrix((4, 4), dtype=np.int8).toarray()
>>> mymat.diagonal()
array([0, 0, 0, 0], dtype=int8)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download