-5

I should convert the following matlab statement in python:

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

Thanks in advance

Linux
  • 3
  • 8

1 Answers1

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
Divakar
  • 218,885
  • 19
  • 262
  • 358