[SciPy-User] Elementwise products of dense and sparse matrices

Jaakko Luttinen jaakko.luttinen@iki...
Thu Feb 16 12:09:53 CST 2012

```Hi!

I am trying to compute elementwise products of dense and sparse
matrices. The products work for two dense matrices or for two sparse
matrices but the product of a dense and a sparse matrix does not work.
See the code below:

>>> import numpy as np
>>> import scipy as sp
>>> A = sp.sparse.csc_matrix(np.identity(5))
>>> B = np.asmatrix(np.ones((5,5)))
>>> np.multiply(A,A)
<5x5 sparse matrix of type '<class 'numpy.float64'>'
with 5 stored elements in Compressed Sparse Column format>
>>> np.multiply(B,B)
matrix([[ 1.,  1.,  1.,  1.,  1.],
[ 1.,  1.,  1.,  1.,  1.],
[ 1.,  1.,  1.,  1.,  1.],
[ 1.,  1.,  1.,  1.,  1.],
[ 1.,  1.,  1.,  1.,  1.]])
>>> np.multiply(B,A)
NotImplemented
>>> np.multiply(A,B)
matrix([[  (0, 0)	1.0
(1, 1)	1.0
(2, 2)	1.0
(3, 3)	1.0
(4, 4)	1.0,
(0, 0)	1.0
(1, 1)	1.0
(2, 2)	1.0
(3, 3)	1.0
(4, 4)	1.0,
.......
(0, 0)	1.0
(1, 1)	1.0
(2, 2)	1.0
(3, 3)	1.0
(4, 4)	1.0]], dtype=object)

So elementwise B*A is not implemented and A*B gives some horrible matrix
with dtype=object.

The A*B or B*A product can be computed as
A.multiply(B)
but it would be more convenient if np.multiply could handle these
situations.

Can this be considered as a bug or missing feature or is there some
rationale behind this?