Enigmacy
Enigmacy

Reputation: 43

dsearchn equivalent in python

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.

Upvotes: 2

Views: 1139

Answers (3)

flumer
flumer

Reputation: 176

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]

Upvotes: 0

Mad Physicist
Mad Physicist

Reputation: 114468

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.

Upvotes: 1

Bruno Mello
Bruno Mello

Reputation: 4618

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])

Upvotes: 1

Related Questions