Convert matlab statement to python -
this question has answer here:
- numpy: find first index of value fast 14 answers
i should convert following matlab statement in python:
lam = find(abs(b)>tol,1,'first')-1;
thanks in advance
numpy doesn't have capability first matching one, not yet anyway
.
so, need matching ones np.where
replace find
, numpy.abs
replacement abs
. thus, -
import numpy np lam = np.where(np.abs(a)>tol)[0][0]-1
thus, getting matching indices np.where(np.abs(a)>tol)[0]
, getting first index indexing first element np.where(np.abs(a)>tol)[0][0]
, subtracting 1
it, 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]: = 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 matlab vesion because of 0-based indexing
for performance, suggest using np.argmax
give index of first matching one, rather computing matching indices np.where(np.abs(a)>tol)[0]
, -
in [40]: np.argmax(np.abs(a)>tol)-1 out[40]: 1
Comments
Post a Comment