Search code examples
pythonarraysnumpyscipysparse-matrix

Convert a Diagonal Sparse Matrix to a 1-D vector


I have a big n-square diagonal matrix, in scipy's sparse DIA format (let's say n = 100000)

D_sparse = sprs.diags(np.ones(100000),0)

I'd like to retrieve the diagonal as a vector (in the numpy array)

But if I do np.diag(D_sparse.toarray()), I get a MemoryError because D_sparse.toarray() generates a huge array quasi-full of 0.

I there a method or a function to get directly the diagonal of D_sparse as an numpy array?


Solution

  • The diagonal method of the dia_matrix object returns the main diagonal.

    For example,

    In [165]: d
    Out[165]: 
    <6x6 sparse matrix of type '<class 'numpy.float64'>'
        with 6 stored elements (1 diagonals) in DIAgonal format>
    
    In [166]: d.A
    Out[166]: 
    array([[ 10.,   0.,   0.,   0.,   0.,   0.],
           [  0.,  11.,   0.,   0.,   0.,   0.],
           [  0.,   0.,  12.,   0.,   0.,   0.],
           [  0.,   0.,   0.,  13.,   0.,   0.],
           [  0.,   0.,   0.,   0.,  14.,   0.],
           [  0.,   0.,   0.,   0.,   0.,  15.]])
    
    In [167]: d.diagonal()
    Out[167]: array([ 10.,  11.,  12.,  13.,  14.,  15.])