1

let said I have two arrays of points, and I want to know what is the distance between each point.

For example:

array_1 = [p1,p2,p3,p4]
array_2 = [p5,p6]

p1 to p6 is point, something like [1,1,1] (3D)

the output I want is

output = [[distance of p1 to p5, distance of p2 to p5, ... distance of p4 to p5], 
          [distance of p1 to p6, distance of p2 to p6, ... distance of p4 to p6]]

what is the best approach if I want to use numpy?

2 Answers 2

2

You can first arange the two arrays into an m×1×3 and an 1×n×3 shape, and then subtract the coordinates:

delta = array_1[:,None] - array_2

Next we can square the differences in the coordinates, and calculate the sum, then we can calculate the square roout:

distances = np.sqrt((delta*delta).sum(axis=2))

Now distances is an m×n matrix with as ij-th element the distance between the i-th element of the first array, and j-th element of the second array.

For example if we have as data:

>>> array_1 = np.arange(12).reshape(-1,3)
>>> array_2 = 2*np.arange(6).reshape(-1,3)

We get as result:

>>> delta = array_1[:,None] - array_2
>>> distances = np.sqrt((delta*delta).sum(axis=2))
>>> distances
array([[ 2.23606798, 12.20655562],
       [ 3.74165739,  7.07106781],
       [ 8.77496439,  2.23606798],
       [13.92838828,  3.74165739]])

The first element of array_1 has coordinates (0,1,2), and the second of array_2 has coordinates (6,8,10). Hence the distance is:

>>> np.sqrt(6*6 + 7*7 + 8*8)
12.206555615733702

This is what we see in the distances array for distances[0,1].

The above function method can calculate the Euclidean distance for an arbitrary amount of dimensions. Given both array_1 and array_2 have points with the same number of dimensions (1D, 2D, 3D, etc.), this can calculate the distances of the points.

Sign up to request clarification or add additional context in comments.

Comments

2

This answer isn't specifically for numpy arrays, but could easily be extended to include them. The module itertools.product is your friend here.

# Fill this with your formula for distance
def calculate_distance(point_1, point_2):
    distance = ...
    return distance

# The itertools module helps here
import itertools
array_1, array_2 = [p1, p2, p3, p4], [p5, p6]

# Initialise list to store answers
distances = []

# Iterate over every combination and calculate distance
for i, j in itertools.product(array_1, array_2):
    distances.append(calculate_distance(i, j)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.