# [SciPy-user] arbitrary submatrices of a sparse matrix?

David Warde-Farley dwf@cs.toronto....
Fri Dec 14 18:21:43 CST 2007

```On 14-Dec-07, at 5:21 AM, Robert Cimrman wrote:

> It works for slices only. Yes, the docstring, as I reread it now, is
> not
> clear. What it should say is, that the slice can be given as:
> 1. slice object
> 2. a tuple (from, to)
> 3. a scalar for single row/column selection
> The method should probably be named _get_submatrix(), as it is used
> internally in __getitem__().

Ah, I figured that out, yes, the tuple is just a start/end point.  I
ended up using the coo_matrix format and just manually do the element
selection and reindexing. I've pasted a copy of my code here, so that
it's in the archives (and so that others may comment and suggest
improvements).

I'll also submit a patch of sparse.py that adds a method for this, in
case the authors think it warrants inclusion.

Cheers,

DWF

def coo_submatrix_pull(matr, rows, cols):
"""
Pulls out an arbitrary i.e. non-contiguous submatrix out of
a sparse.coo_matrix. This does create a copy, however, which
is probably not ideal.
"""
if type(matr) != S.sparse.coo_matrix:
raise TypeError('Matrix must be sparse COOrdinate format')

gr = -1 * ones(matr.shape[0])
gc = -1 * ones(matr.shape[1])

lr = len(rows)
lc = len(cols)

ar = arange(0, lr)
ac = arange(0, lc)
gr[rows[ar]] = ar
gc[cols[ac]] = ac

newelem = (gr[matr.row] > -1) & (gc[matr.col] > -1)
newrows = matr.row[newelem]
newcols = matr.col[newelem]

return S.sparse.coo_matrix((matr.data[newelem],
array([gr[newrows], \
gc[newcols]])),(lr, lc))
```