scipy sparse matrix -- accessing multiple elements of a path

153 views Asked by At

I have a scipy sparse matrix A and a (long) list of coordinates

myrows=[i1,i2,...] mycols=[j1,j2,...]. I need a list of their values [A[i1,j2],A[i2,j2],...]. How can I do this quickly. A loop is too slow.

I've thought about cython.inline() (which I use in other places in my code) or weave, but I don't see how to use the sparse type efficiently in cython or C++. Am I missing something simple?

Currently I'm using a hack that seems inefficient and possibly wrong sometimes -- which I flag with an error message. Here is my badly written code. Note that it relies on the ordering of elements to be preserved under addition and assumes that the elements in myrows,mycols are in A.

import scipy.sparse as sps
def getmatvals(A,myrows,mycols)  #A is a coo_matrix
    B = sps.coo_matrix((range(1,1+A.nnz),(A.row,A.col)),shape=A.shape)
    T =  sps.coo_matrix(([A.nnz+1]*len(myrows),(myrows,mycols)),shape=A.shape)
    G = B-T  #signify myelements in G by negatives and others by 0's
    H = np.minimum([0]*A.nnz,G.data)  #remove extra elements 
    H = H[np.nonzero(H)]
    H = H + A.nnz
    return A.data[H]
0

There are 0 answers