Search code examples
pythonnumpyscipymatrix-indexing

modifying sparse matrix using advanced indexing in python


I'm trying to use advanced indexing to modify a big sparse matrix. Say you have the following code:

import numpy as np
import scipy.sparse as sp

A = sp.lil_matrix((10, 10))
a = np.array([[1,2],[3,4]])

idx = [1,4]
A[idx, idx] += a

Why this code doesn't work? It gives me the error

ValueError: shape mismatch in assignment

Solution

  • For idx = [1,4], A[idx, idx] returns a sparse matrix of shape (1,2) with the elements A[1,1] and A[4,4]. However, a has shape (2,2). Therefore, there is a mismatch in shape. If you want to assign A[1,1], A[1,4], A[4,1] and A[4,4] to a, you should do:

    import numpy as np
    import scipy.sparse as sp
    
    A = sp.lil_matrix((10, 10))
    a = np.array([[1,2],[3,4]])
    
    idx = np.array([1,4])
    A[idx[:, np.newaxis], idx] += a  # use broadcasting