jaco
jaco

Reputation: 21

Finding row indices corresponding to a specific value on a diagonal in sparse matrices

I had a question related to sparse matrices. I start with a matrix A:

import numpy as np
A =  np.array([[ 2,  0,  0, -1,  0, -1],
       [ 0,  4, -1,  2, -1,  0],
       [ 0, -1,  3, -1,  1, -1],
       [-1,  2, -1,  3, -1, -1],
       [ 0, -1,  1, -1,  2,  0],
       [-1,  0, -1, -1,  0,  1]])

then I generate a sparse matrix (this is an example, the matrices I work with have 10k plus entries)

import scipy as sparse
M = sparse.csr_matrix(A)

Now, from this I will need to extract the diagonal (no problem there)

M.diagonal()
Out: array([2, 4, 3, 3, 2, 1])

And.. here is where I am stuck...

From the diagonal I would like to check all entries with a specific value, let's say 4, and assess all row indices where 4 is found on the diagonal. IN this specific example, this should yield something like: [1]

From those indices I need to assess all row values (excluding the diagonal) of the sparse matrix, and find the maximum value, that, in this case, should be = 2.

Another example, if I look for 2, row indices should be: [0],[4], and maximum value = 0 (as 0 is the max value in rows 0, and 4 of the sparse matrix).

Any help would be greatly appreciated!

Upvotes: 2

Views: 144

Answers (1)

David Wierichs
David Wierichs

Reputation: 545

You can access the indices in which the diagonal is equal to some value, say val, via

indices = M.diagonal()==val

Then we can remove the diagonal from M via the accepted answer of this question:

M -= sparse.dia_matrix((M.diagonal()[scipy.newaxis, :], [0]), shape=M.shape)

and finally find the maximum of the rows of the modified M selected via indices:

np.max(M[indices])

Upvotes: 1

Related Questions