Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find function matlab in numpy/scipy

Is there an equivalent function of find(A>9,1) from matlab for numpy/scipy. I know that there is the nonzero function in numpy but what I need is the first index so that I can use the first index in another extracted column.

Ex: A = [ 1 2 3 9 6 4 3 10 ] find(A>9,1) would return index 4 in matlab

like image 700
user1988634 Avatar asked Jan 17 '13 21:01

user1988634


3 Answers

The equivalent of find in numpy is nonzero, but it does not support a second parameter. But you can do something like this to get the behavior you are looking for.

B = nonzero(A >= 9)[0] 

But if all you are looking for is finding the first element that satisfies a condition, you are better off using max.

For example, in matlab, find(A >= 9, 1) would be the same as [~, idx] = max(A >= 9). The equivalent function in numpy would be the following.

idx = (A >= 9).argmax()
like image 103
Pavan Yalamanchili Avatar answered Oct 07 '22 09:10

Pavan Yalamanchili


matlab's find(X, K) is roughly equivalent to numpy.nonzero(X)[0][:K] in python. @Pavan's argmax method is probably a good option if K == 1, but unless you know apriori that there will be a value in A >= 9, you will probably need to do something like:

idx = (A >= 9).argmax()
if (idx == 0) and (A[0] < 9):
    # No value in A is >= 9
    ...
like image 38
Bi Rico Avatar answered Oct 07 '22 09:10

Bi Rico


I'm sure these are all great answers but I wasn't able to make use of them. However, I found another thread that partially answers this: MATLAB-style find() function in Python

John posted the following code that accounts for the first argument of find, in your case A>9 ---find(A>9,1)-- but not the second argument.

I altered John's code which I believe accounts for the second argument ",1"

def indices(a, func):
    return [i for (i, val) in enumerate(a) if func(val)]
a = [1,2,3,9,6,4,3,10]
threshold = indices(a, lambda y: y >= 9)[0]

This returns threshold=3. My understanding is that Python's index starts at 0... so it's the equivalent of matlab saying 4. You can change the value of the index being called by changing the number in the brackets ie [1], [2], etc instead of [0].

John's original code:

def indices(a, func):
    return [i for (i, val) in enumerate(a) if func(val)]

a = [1, 2, 3, 1, 2, 3, 1, 2, 3]

inds = indices(a, lambda x: x > 2)

which returns >>> inds [2, 5, 8]

like image 1
Clayton Pipkin Avatar answered Oct 07 '22 08:10

Clayton Pipkin