[SciPy-user] broadcasting elementwise on sparse matrix

Stéfan van der Walt stefan@sun.ac...
Wed Oct 1 09:58:38 CDT 2008

Hi Robin

2008/10/1 Robin <robince@gmail.com>:
> Is there any way to get broadcasted element wise operations on sparse matrices?
> I would like to do something like A * x if A was (n,n) array and x was
> a (n,) array. I saw the sparse matrices have a .multiply method, but
> it doesn't seem to broadcast in the same way as the standard
> multiplication, ie As.multiply(x) gives an "inconsistent shapes"
> error.
> The best I have is As.multiply(tile(x,(n,1))) although this has the memory
> overhead that is normally avoided with broadcasting. Is there an alternative?

You can broadcast over the indices, and then use them to individually
address the elements of the sparse matrix.  Not super-fast, but better
than nothing:

In [4]: a, b = np.broadcast_arrays([1,2,3], [[1,2,3], [4,5,6]])

In [5]: a
array([[1, 2, 3],
       [1, 2, 3]])

In [6]: b
array([[1, 2, 3],
       [4, 5, 6]])


More information about the SciPy-user mailing list