Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract the main diagonal of a sparse matrix?

How can I extract the main diagonal of a sparse matrix? The matrix is created in scipy.sparse. I want equivalent of np.diagonal(), but for sparse matrix.

like image 493
AnandJ Avatar asked Jan 19 '16 06:01

AnandJ


People also ask

How do you extract the diagonal elements of a matrix?

Description. D = diag( v ) returns a square diagonal matrix with the elements of vector v on the main diagonal. D = diag( v , k ) places the elements of vector v on the k th diagonal. k=0 represents the main diagonal, k>0 is above the main diagonal, and k<0 is below the main diagonal.

What is diagonal sparse matrix?

In a Lower triangular sparse matrix, all elements above the main diagonal have a zero value. This type of sparse matrix is also known as a lower triangular matrix. If you see its pictorial representation, then you find that all the elements having non-zero value are appear below the diagonal.


1 Answers

A sparse matrix has a diagonal method:

M.diagonal()

http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csc_matrix.diagonal.html

The numpy diagonal is a little more powerful, allowing you to specify an off diagonal

M.A.diagonal(2)
like image 90
hpaulj Avatar answered Oct 24 '22 20:10

hpaulj