[Scipy-tickets] [SciPy] #1859: Sparse matrix subtraction with another matrix seems to regard the other matrix as a scalar

SciPy Trac scipy-tickets@scipy....
Fri Mar 1 20:30:13 CST 2013

```#1859: Sparse matrix subtraction with another matrix seems to regard the other
matrix as a scalar
------------------------------------+---------------------------------------
Reporter:  photon.engine           |       Owner:  jakevdp
Type:  defect                  |      Status:  new
Priority:  normal                  |   Milestone:  Unscheduled
Component:  scipy.sparse            |     Version:  0.10.1
Keywords:  sparse scalar subtract  |
------------------------------------+---------------------------------------

Comment(by warren.weckesser):

`numpy.dot` does not handle scipy's sparse matrices.
Since `matrix` is a sparse matrix, instead of writing
`numpy.dot(matrix, solution)`, you should use either `matrix * solution`
or `matrix.dot(solution)`.

If `matrix` had been, say, a CSR matrix, the code would have crashed
when `numpy.dot` was called.   The DIA matrix doesn't crash, but it
doesn't
work.

Here's an example:

{{{
In [1]: from scipy.sparse import csr_matrix

In [2]: m = csr_matrix([[1,0,0],[2,3,0],[0,0,4]])

In [3]: m.toarray()
Out[3]:
array([[1, 0, 0],
[2, 3, 0],
[0, 0, 4]])

In [4]: b = array([10, 20, 30])

In [5]: np.dot(m, b)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call
last)
<ipython-input-5-0832d925df98> in <module>()
----> 1 np.dot(m, b)

ValueError: setting an array element with a sequence.
}}}
So using np.dot with a CSR matrix fails.
With a DIA matrix, however...
{{{
In [6]: d = m.todia()

In [7]: y = np.dot(d, b)

In [8]: y
Out[8]:
array([ <3x3 sparse matrix of type '<type 'numpy.int64'>'
with 5 stored elements (2 diagonals) in DIAgonal format>,
<3x3 sparse matrix of type '<type 'numpy.int64'>'
with 5 stored elements (2 diagonals) in DIAgonal format>,
<3x3 sparse matrix of type '<type 'numpy.int64'>'
with 5 stored elements (2 diagonals) in DIAgonal format>],
dtype=object)

In [9]: y[0].toarray()
Out[9]:
array([[10,  0,  0],
[20, 30,  0],
[ 0,  0, 40]])

In [10]: y[1].toarray()
Out[10]:
array([[20,  0,  0],
[40, 60,  0],
[ 0,  0, 80]])

}}}
`numpy.dot` returned a numpy array of the correct shape, but
it is of type 'object', and the contents are not what we expect.

--
Ticket URL: <http://projects.scipy.org/scipy/ticket/1859#comment:1>
SciPy <http://www.scipy.org>
SciPy is open-source software for mathematics, science, and engineering.
```