# [Numpy-discussion] Sparse matrices

Victor S. Miller victor at idaccr.org
Tue Jul 30 06:43:06 EDT 2002

```I had noticed that Travis Oliphant had a sparse.py package, but it no
longer is available (clicking on the link gives a "404").  I have a
particular kind of sparse matrix that I'd like to use to give vector
matrix multiplies.  In particular, it's an n x n matrix which has at
most k (which is small, usually 2 or 3) non-zeros in each row which
are in consecutive locations.  I have this encoded as an n x k matrix,
the i-th row gives the non-zero values in the i-th row of the big
matrix, and an n long vector of indices -- the i-th element gives the
starting position in the i-th row.  When I want to multiply this
matrix by a row vector v on the left.  To do the multiplication I do
the following:

# loc is the location vector
n = matrix.shape
mm = reshape(v,(-1,1))*matrix
w = zeros((n+m),v.typecode())
for i in range(mm.shape):
w[loc[i]:loc[i]+matrix.shape] += w[i]
w = w[:n]

I would like to be able to replace the loop with some Numeric
operations.  Is there a trick to do this?  Note that the n that I'm
using is around 100000, so that storing the full matrix is out of the
question (and multiplying by that matrix would be extremely
inefficient, anyway).
--
Victor S. Miller     | " ... Meanwhile, those of us who can compute can hardly
victor at idaccr.org    | be expected to keep writing papers saying 'I can do the
CCR, Princeton, NJ   | following useless calculation in 2 seconds', and indeed
08540 USA        | what editor would publish them?"  -- Oliver Atkin

```