[SciPy-user] nonzero and the matlab equivalent of find
Robert Kern
robert.kern@gmail....
Sun Jul 12 17:03:47 CDT 2009
On Sun, Jul 12, 2009 at 16:51, per freem<perfreem@gmail.com> wrote:
> hi all,
>
> i am trying to find an equivalent of matlab's find in scipy. the
> documentation says to use nonzero but i am not sure how to interpret the
> results.
>
> suppose i have an array:
>
> a = [[0, 1], [1, 1], [1, 0]]
>
> and i want to return the indices (0, 1, or 2 in this case) of the elements
> that are [1, 1]. the natural notation seems to be:
>
> nonzero(a == array([1, 1]))
>
> but this returns: (array([0, 1, 1, 2]), array([1, 0, 1, 0])) -- not sure
> what this output means.
Well, let's take a look at the intermediate value of a==array([1,1]):
In [24]: a = array([[0,1], [1,1], [1,0]])
In [25]: a == array([1, 1])
Out[25]:
array([[False, True],
[ True, True],
[ True, False]], dtype=bool)
The result of nonzero(), when given a multidimensional array is to
return a tuple with the indices for each dimension such that:
In [26]: a[nonzero(a == array([1,1]))]
Out[26]: array([1, 1, 1, 1])
> can someone please explain how to find the elements that are [1,1], like in
> matlab's "find"? thank you.
There isn't really a function that does this out-of-box, but here is
how to do it:
In [30]: nonzero((a[:,0] == 1) | (a[:,1] == 1))[0]
Out[30]: array([0, 1, 2])
--
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 SciPy-user
mailing list