2

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
aaragon
  • 2,314
  • 4
  • 26
  • 60
  • With a dense array, the same operation has the same problem, though the error message is: `ValueError: non-broadcastable output operand with shape (2,) doesn't match the broadcast shape (2,2)`. Are you trying to set a diagonal, or a square of values? – hpaulj Jul 01 '16 at 16:20
  • I was trying to set a sub-matrix of A with the values of a. – aaragon Jul 01 '16 at 18:41

1 Answers1

3

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
edwinksl
  • 7,005
  • 4
  • 30
  • 36