[SciPy-user] probably a stupid question: MatLab equivalent of "diff" ?

Tom Denniston tom.denniston at alum.dartmouth.org
Fri Dec 29 12:58:36 CST 2006


Does this help?

In [5]: numpy.diff(numpy.array([True,True,False,False,True,True], dtype=int))
Out[5]: array([ 0, -1,  0,  1,  0])

or if a is already defined:

In [7]: numpy.diff(numpy.array([True,True,False,False,True,True], dtype=int))
Out[7]: array([ 0, -1,  0,  1,  0])

In [8]: a=numpy.array([True,True,False,False,True,True])

In [9]: a
Out[9]: array([True, True, False, False, True, True], dtype=bool)

In [10]: a.astype(int)
Out[10]: array([1, 1, 0, 0, 1, 1])

In [11]: numpy.diff(a.astype(int))
Out[11]: array([ 0, -1,  0,  1,  0])



On 12/29/06, Stef Mientki <s.mientki at ru.nl> wrote:
> hi Tom,
>
> Tom Denniston wrote:
> > It would help if you could give a concrete example with a small set of
> > data as below to demonstrate the problem:
> >
> >
>  >>> # the orginal array
>  >>> a = array([True,True,False,False,True,True])
>
>  >>> B = numpy.diff(a)
>  >>> B
> array([False, True, False, True, False], dtype=bool)
>  >>> # now elements B[1] and B [3] are true, so both edges
>
>  >>> # that doesn't seem to be unlogical, if we try to subtract booleans
>  >>> True - False
> 1
>  >>> False - True
> -1
>
> And now I guess that both -1 and +1 are translated into True,
> and can't be distinguished anymore :-(
>
>  >>> # and now also this doesn't work: again 2 edges
>  >>> a[1:] - a[:-1]
> array([False, True, False, True, False], dtype=bool)
>  >>> a[1:] - a[:-1]  > 0
> array([False, True, False, True, False], dtype=bool)
>
>  >>> # So the first thing that worked:
>  >>> a[1:] &  ~(a[:-1])
> array([False, False, False, True, False], dtype=bool)
>
> And that was (besides the history element) the solution I posted in the
> previous mail.
> Due to some typing error, I thought my editor didn't except the "&" and
> "~ ",
> and therefore I used the longer logical_and, logical_not.
>
> Now I can live quiet well with this,
> but as Newbie I want to know that's the correct way,
> or are their better ways ?
>
> thanks,
> Stef
>
> _______________________________________________
> SciPy-user mailing list
> SciPy-user at scipy.org
> http://projects.scipy.org/mailman/listinfo/scipy-user
>


More information about the SciPy-user mailing list