k.dav
k.dav

Reputation: 59

Calculate the distance between all point in an array and another point in two dimensions

I have a two dimensional point, lets call it

p1 = (x,y)

and an array of points,

p2 = [(x1, y1), (x2, y2), (x3, y3)...]

I want to build an array that calculates the distance between each entry in p2 and the point p1. Next, I need to find the smallest distance between a point in p2 and p1 and return the original coordinates in p2. So far, I have tried the following:

dist1 = np.sqrt(p1.x**2 + p1.y**2)
dist2 = np.sqrt(p2.x**2 + p2.y**2)
dist = dist2-dist1

Which returns the error "operands could not be broadcast together with shapes (2,) (1265,)"

As far as finding the minimum distance, I think I need to use the numpy min function as follows

import numpy as np
np.min(dist)

But I am stuck on how to return the x nd y coordinates once I calculate the distance.

Upvotes: 0

Views: 12937

Answers (2)

bumblebee
bumblebee

Reputation: 1841

If you wanna calculate the distance and find the smallest without using any package, then you can try something like this

import sys

minimum_distance = sys.maxsize
minimum_point = (0,0)

for point in p2:
    distance = math.sqrt((p[0] - point[0]) ** 2 + (p[1] - point[1]) ** 2)
    if distance < minimum_distance:
        minimum_distance = distance
        minimum_point = point

print("Point with minimum distance", minimum_point)

Upvotes: 0

JARS
JARS

Reputation: 1129

Normally you use scipy's cdist to achieve this, but you need to specify the arrays in a different format.

Example:

import numpy as np
from scipy.spatial.distance import cdist

x = np.array([[2,1]])
y = np.array([[1,0], [2,3], [4,3]])

d = cdist(x,y)

And d is the array with all the distances.

In general, when specifying sets of points, the format p2 = [(x1, y1), (x2, y2), (x3, y3)...] is not very convenient for manipulation with libraries such as numpy / scipy / pandas. Typically you might prefer np.array([[x1,y1], [x2,y2], [x3,x3]]) instead.

To get the minimum distance, use

idx = np.argmin(d)

idx returns the value of the index of the array with the minimum distance (in this case, 0).

So if you do y[idx] it will return the point with minimum distance (in this case [1, 0]).

Upvotes: 3

Related Questions