Search code examples
pythonscipysparse-matrix

Python Sparse matrix access elements


I have a sparse matrix A in python. I m going through code of a friend of mine and he uses A[:,i:i+1].toarray().flatten() in his code. As far as I m concerned, the program worked for him. However when I try to use it, I get:

from scipy import sparse

...

diagonals = [[2] * 3, [-1] * (3-1), [-1] * (3-1)]
offsets = [0, 1, -1]
B = sparse.diags(diagonals, offsets)
A = sparse.kronsum(B,B)

...
A[:,i:i+1].toarray().flatten()

Exception:

    in __getitem__
        raise NotImplementedError
    NotImplementedError

My question, what to I need to implement or how could I access elements of a sparse matrix. Thanks for the help.


Solution

  • Most likely you have a bsr format matrix, while the code you have, was implemented using an older version of scipy and returns a csr or csc matrix. I don't know a good way of tracing this.

    So if we run you code on scipy 1.7.2 :

    type(A)
    scipy.sparse.bsr.bsr_matrix
    

    We can access the elements by:

    A = sparse.kronsum(B,B,format = "csr")
    A[:,i:i+1].toarray().flatten()
    
    array([-1.,  4., -1.,  0., -1.,  0.,  0.,  0.,  0.])
    

    Or

    A = sparse.kronsum(B,B)
    A.tocsr()[:,i:i+1].toarray().flatten()