lasha
lasha

Reputation: 43

finding nearest points in python

I started using Python recently so maybe this is a stupid question, but anyway:

I have two arrays C and X. Each array elements are two dimensional points.

for example:

C = [[1,1], [10,10]]

X = [[1,2], [1,3], [2,1], [10,11], [10,12], [11,11], [12,11], [9,11]]

I want to group points from X around nearest (euclidean distance) points in C.

for example nearest point from C for element 1 of X([1,2]) is first element of C( [1,1]),

for second element of X ([1,3]) - again first element of C([1,1])

...

for last element in X([9,11]) - second element in C([10,10])

so [1,1] is nearest element for 3 points form X, and [10, 10] is nearest for 5 elements from X.

I want a function in python F(C,X) that will return for every element of C, the number of elements from X to whom this element of C is nearest. So in this example it should return [3,5].

I can write my own function but it will not be effective, so I'm interested if there is any predefined function in Python for my problem?

Thank you

Upvotes: 2

Views: 1264

Answers (1)

Sait
Sait

Reputation: 19855

There might be a faster, but this do the work:

import numpy as np

C = [[1,1], [10,10]]
X = [[1,2], [1,3], [2,1], [10,11], [10,12], [11,11], [12,11], [9,11]]

def F(C,X):
    Carr = np.array(C)
    Xarr = np.array(X)
    distances = [np.sum( (Xarr - Carr[i])**2, axis=1) for i in range(len(C))]
    closests = np.argmin( np.array(distances), axis=0 )
    return list( np.bincount(closests) )

print(F(C,X))

will print:

[3, 5]

Upvotes: 2

Related Questions