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 th
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]
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, B] = max(A >= 9)
. The equivalent function in numpy would be the following.
idx = (A >= 9).argmax()
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
...