[Numpy-discussion] Translation of Matlab function find()
Robert Kern
robert.kern@gmail....
Wed Mar 21 14:08:56 CDT 2007
Miquel Poch wrote:
> Hi,
>
> I'm trying to translate some Matlab functions. I don't know exactly how
> make and equivalent for function find(). This give us the index of an
> array where a condition it's true.
>
> I've found some options like this one: (a>0).nonzero(), where a is the
> array and (a>0) the condition. But the problem appear with this function
> return. It's something like this:
>
>>>> from numpy import *
>>>> a=array([0,1,0,1,2,0,1,2,0,0])
>>>> print a
> [0 1 0 1 2 0 1 2 0 0]
>>>> b=(a>0).nonzero()
>>>> print b
> (array([1, 3, 4, 6, 7]),)
>>>> print (a>0).nonzero()
> (array([1, 3, 4, 6, 7]),)
>
> I can't acces to b data, doing something like b[x]. Why b is not an array?
Because when `a` is a multi-dimensional array, the result of (a>0).nonzero()
must be a tuple. For consistency's sake, the result of .nonzero() (and
where(a>0) for that matter) is always a tuple even if it just has a single
element. Thus, you probably want
b = (a>0).nonzero()[0]
> I think another possible is use where() function, also avilable in numpy
> library. It's better or worse?
More or less the same. It's possibly more straightforward to read.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Numpy-discussion
mailing list