find function matlab in numpy/scipy

前端 未结 3 615
不思量自难忘°
不思量自难忘° 2021-02-15 06:09

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

相关标签:
3条回答
  • 2021-02-15 06:55

    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]

    0 讨论(0)
  • 2021-02-15 07:10

    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()
    
    0 讨论(0)
  • 2021-02-15 07:17

    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
        ...
    
    0 讨论(0)
提交回复
热议问题