# [SciPy-User] numpy.diff of sparse matrix

Jason Rennie jrennie@gmail....
Tue Sep 7 15:27:26 CDT 2010

```My experience is similar to yours---numpy doesn't work with scipy sparse
matrices.  Not even numpy.dot does the right thing.  My guess is that you'd
want to write the sparse diff for the sparse library.  An example of how to
organize such function is the sparse hstack:

http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.hstack.html

Cheers,

Jason

On Tue, Sep 7, 2010 at 2:49 PM, Jonathan Stickel <jjstickel@vcn.com> wrote:

> I'd like to use numpy.diff on a sparse matrix, but I get the following:
>
>
> In [76]: np.diff(np.identity(3),axis=0)
> Out[76]:
> array([[-1.,  1.,  0.],
>        [ 0., -1.,  1.]])
>
> In [77]: np.diff(sparse.identity(3),axis=0)
> ---------------------------------------------------------------------------
> IndexError                                Traceback (most recent call last)
>
> /Users/jstickel/temp/<ipython console> in <module>()
>
>
> /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/numpy/lib/function_base.pyc
> in diff(a, n, axis)
>     961     slice1 = [slice(None)]*nd
>     962     slice2 = [slice(None)]*nd
> --> 963     slice1[axis] = slice(1, None)
>     964     slice2[axis] = slice(None, -1)
>     965     slice1 = tuple(slice1)
>
> IndexError: list assignment index out of range
>
>
> I suppose numpy.diff doesn't know how to handle a sparse matrix object.
>  Converting to dense would work, but that would defeat the purpose of
> using sparse matrices.  Any quick solutions?  I don't have time now, but
> if I were to implement a sparse diff, should it go within numpy.diff or
> be a separate function (maybe scipy.sparse.spdiff)?
>
> Thanks,
> Jonathan
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>

--
Jason Rennie
Research Scientist, ITA Software
617-714-2645
http://www.itasoftware.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20100907/422d846d/attachment.html
```

More information about the SciPy-User mailing list