-5

I should convert the following matlab statement in python:

lam = find(abs(b)>tol,1,'first')-1; 

Thanks in advance

1
  • It would be useful if you provide some 'actual' b, tol and show what Matlab does Commented Apr 7, 2017 at 11:03

1 Answer 1

1

NumPy doesn't have the capability to get the first matching one, not yet anyway.

So, we need to get all matching ones with np.where to replace find and numpy.abs would be the replacement for abs. Thus, it would be -

import numpy as np

lam = np.where(np.abs(a)>tol)[0][0]-1

Thus, we are getting all matching indices with np.where(np.abs(a)>tol)[0], then getting the first index by indexing into its first element with np.where(np.abs(a)>tol)[0][0] and finally subtracting 1 from it, just like we did on MATLAB.

Sample run -

On MATLAB :

>> b = [-4,6,-7,-2,8];
>> tol = 6;
>> find(abs(b)>tol,1,'first')-1
ans =
     2

On NumPy :

In [23]: a = np.array([-4,6,-7,-2,8])

In [24]: tol = 6

In [25]: np.where(np.abs(a)>tol)[0][0]-1
Out[25]: 1 # 1 lesser than MATLAB vesion because of 0-based indexing

For performance, I would suggest using np.argmax to give us the index of the first matching one, rather than computing all matching indices with np.where(np.abs(a)>tol)[0], like so -

In [40]: np.argmax(np.abs(a)>tol)-1
Out[40]: 1
Sign up to request clarification or add additional context in comments.

4 Comments

argmax fails if there is no first element
Anf if I want the "last" instead of the "first" ?
@Linux np.where(np.abs(a)>tol)[0][-1].
Ah ok . Thank you very much for your kind support.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.