Search code examples
pythonnumpymatrixscipysparse-matrix

Accessing non-zero elements in specific row of matrix in python


I have the indices of the positions of non-zero elements in a sparse matrix in python in the form

(array([0, 1, 2], dtype=int32), array([2, 0, 0], dtype=int32), array([2, 1, 3]))

or in the matrix form

[[0 2]
 [1 0]
 [2 0]]

I want to use this (or some other method if there is one) to carry out row-by-row operations with only the corresponding non-zero elements of other matrices, like so:

for r in range(rows):
    A[r,:] = np.dot(B[r,:],C.T)

Basically I need a way to specify the row and only choose the elements from that row that correspond to the non-zero elements from the matrix B.

The part I can't get my head around is due to the fact that there can be a varying number of entries for each row/column.


Solution

  • I found out you can use boolean array indices in python so the following does what I wanted to achieve:

    for r in range(rows):
        A[r,B[r,:]!=0] = np.dot(B[r , B[r,:]!=0], C[: , B[r,:]!=0].T)
    

    looks kind of complicated but it gets the right elements for the calculation. The only problem is when the dimension of B is larger than what it's indexing into which throws an index out of bounds error.