# [SciPy-User] Finding closest point in array - inverse of KDTree

Xavier Barthelemy xabart at gmail.com
Wed Oct 11 19:16:37 EDT 2017

```Hi Antonio,

I think yo are looking for the scipy.spatial.distance_matrix function

I used it inside a wave crest tracking algorithm  (on probably a much
smaller matrix than your), but unfortunately, there is no magical method to
reduce significantly the computation time.

Have a go at it

Xavier

2017-10-12 7:13 GMT+11:00 Daπid <davidmenhur at gmail.com>:

> On 11 October 2017 at 19:01, Antonio Polino <antoniy.py at gmail.com> wrote:
>
>> On the other hand, the array A is always the same, only k changes. So it
>> would be beneficial to use some auxiliary structure (like a "inverse
>> KDTree") on A, and then query the results on the small array k.
>>
>
> You can sort A and use searchsorted to find the positions of the midpoints
> of k. Then, you assign the values to the group.
>
>
>     >>> A = np.asarray([3, 4, 5, 6])
>     >>> k = np.asarray([3, 4.1, 5.2])
>     >>> midpoints = np.array([ 3.55,  4.65])   #  k[:-1] + np.diff(k) / 2
>     >>> np.searchsorted(A, midpoints)
>     array([1, 2])
>
> So, this means that A[:1] belong to k[0], A[1:2] belong to k[2] and A[2:]
> belong to k[3]
>
>
> /David.
>
> PS: in your later email I see your name as Ant.
>
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at python.org
> https://mail.python.org/mailman/listinfo/scipy-user
>
>

--
« Quand le gouvernement viole les droits du peuple, l'insurrection est,
pour le peuple et pour chaque portion du peuple, le plus sacré des droits
et le plus indispensable des devoirs »

Déclaration des droits de l'homme et du citoyen, article 35, 1793
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/scipy-user/attachments/20171012/309e6a67/attachment.html>
```