Is there a Scipy or Numpy function that does the job of dsearchn MATLAB command in python?
dsearchn returns the index of nearest value to the input value in the given vector.
Is there a Scipy or Numpy function that does the job of dsearchn MATLAB command in python?
dsearchn returns the index of nearest value to the input value in the given vector.
You can do something like:
x = np.array([1.1, 1.2, 1.22, 1.4])
v = 1.21
def dsearchnn(x, v):
return np.where(np.abs(x-v) == np.abs(x-v).min())[0]
dsearchnn(x, v)
array([1,2])
A method of approximately equivalent efficiency is probably scipy's KDTree or better yet cKDTree:
from scipy.spatial import KDTree
kdt = KDTree(P.T)
kdt.query(PQ.T)
Here P and PQ are the points and query points from the dsearch docs. MATLAB uses the first dimension as the dimensionality of the points, while scipy uses the last, hence the transpose.
Unlike the MATLAB approach, which is done in a single step, using a KDTree us done in two steps: first you construct the tree object, then you run a query on it.
for x and v are both vectors:
def dsearchn(x, v):
z=np.atleast_2d(x)-np.atleast_2d(v).T
return np.where(np.abs(z).T==np.abs(z).min(axis=1))[0]