# [SciPy-user] Sparse matrices and array multiplication

Nathan Bell wnbell@gmail....
Sun Jan 27 09:23:32 CST 2008

```On Jan 27, 2008 7:20 AM, Christopher Mutel <cmutel@gmail.com> wrote:

> By array multiplication, I mean:
> a = [a1, a2]
> b = [[b1, b2], [b3, b4]]
> a*b = [[a1*b1, a2*b2], [a1*b3, a2*b4]]
>
> I am using relatively large arrays, about 1500*4000, with a 1-d
> multiplying vector of length 1500, but with only about 1-2% coverage
> in both, so populating NumPy arrays means lots of wasted space, or
> even exhausts available memory when considering ~20 arrays
> simultaneously.

To do this with sparse matrices you can put the entries of 'a' on the
diagonal of a matrix and use it to scale the columns of b.

from scipy.sparse import *
a = spdiag( [a], [0], 2, 2)  # a is now [[a1,0],[0,a2]] in sparse format
b*a  #should be [[a1*b1, a2*b2], [a1*b3, a2*b4]]

In practice, (a * b.T).T may be faster here, so you might try that one too.

--
Nathan Bell wnbell@gmail.com
http://graphics.cs.uiuc.edu/~wnbell/
```