[SciPy-User] setting submatrix of sparse matrix

Fri Apr 20 14:07:24 CDT 2012

```Hi,

I am developing a simple Finite Elements code and there a part of the code
where I need to set some elements of the sparse matrix (actually a submatrix),
But I could not make it work. I have tried many ways.

I describe the better way I could try. The array index  idx   is 1x3,
so idx1 and idx2 is 3x3.
The (small) matrix M is 3x3.  The matrix A is a sparse matrix,
lil_matrix sparse matrix of scipy.sparse

###### partial code ##################

M = local_matrix(x,y)
M=M.ravel()

idx1,idx2 = numpy.meshgrid(idx,idx)
idx1=idx1.ravel()
idx2=idx2.ravel()

A[idx1,idx2] = A[idx1,idx2] + M

###################################

In fact, I am trying to migrate from MATLAB to Scipy/Numpy, but this
part is taking some time and is
becoming frustrating, since I could not find any kind of way to
In MATLAB, the code would be just:

M = local_matrix(x,y)
A[idx,idx] = A[idx,idx] + M

Which is shorter and easy.   I send next the error message. Any help
is welcome.  Thanks,  Duilio

131     idx2=idx2.ravel()
132
--> 133     A[idx1,idx2] = A[idx1,idx2] + M

/usr/lib/python2.6/dist-packages/scipy/sparse/lil.pyc in
__setitem__(self, index, x)
318             else:
319                 for ii, jj, xx in zip(i, j, x):
--> 320                     self._insertat(ii, jj, xx)
321         elif isinstance(i, slice) or issequence(i):
322             rows = self.rows[i]

/usr/lib/python2.6/dist-packages/scipy/sparse/lil.pyc in
_insertat(self, i, j, x)
230         row = self.rows[i]
231         data = self.data[i]
--> 232         self._insertat2(row, data, j, x)
233
234     def _insertat2(self, row, data, j, x):

/usr/lib/python2.6/dist-packages/scipy/sparse/lil.pyc in
_insertat2(self, row, data, j, x)
244
245         if not np.isscalar(x):
--> 246             raise ValueError('setting an array element with a sequence')
247
248         try:

ValueError: setting an array element with a sequence
```