How to distance between all points in list?

Question:

I am plotting random points on a graph. I want to find the Eucildean distance from every point to another in a list.

Previous result/attempt can be viewed here

I generate 4 random numbers between 0 and 10 for the x and y coordinates, and then pair them using np.array. I need use distance formula and a nested loop to calculate the distance between two points in the list. This generates 8 values, which I assume is the distances. As there is 4 points, there should be 6 distances between the points.

Am I programming in the distance forumla incorrectly? Or am I defining the points incorrectly?

Code below

import numpy as np
import matplotlib.pyplot as plt
import random
import math

dist = []

x = [random.uniform(1, 10) for n in range(4)]
y = [random.uniform(1, 10) for n in range(4)]
plt.scatter(x, y)
plt.show()

pairs = np.array([x, y])

def distance(x, y):
    return math.sqrt((x[0]-x[1])**2 + (y[0]-y[1])**2)

for x in pairs:
    for y in pairs:
        d = distance(x, y)
        dist.append(d)
        
print(pairs)
Asked By: Yeknic

||

Answers:

You can try the code below to achieve calculating the distance between each pair of points

import random
import math

dist = []

x = [random.uniform(1, 10) for n in range(4)]
y = [random.uniform(1, 10) for n in range(4)]

pairs = list(zip(x,y))


def distance(x, y):
    return math.sqrt((x[0]-x[1])**2 + (y[0]-y[1])**2)

for i in range(len(pairs)):
    for j in range(i+1,len(pairs)):
        dist.append(distance(pairs[i],pairs[j]))

print(dist)
        
Answered By: anas laaroussi

You can use numpy broadcasting to create a distance matrix where the entry at (i,j) is the distance from i-th point to j-th point. Try to avoid Python loops if possible as they are comparatively slow.

a = np.random.uniform(size=(4,2,1))  # coordinate of i-th point is a[i, :, 0]
np.sqrt(np.sum(np.square(a - a.T), axis=1))
Answered By: bui
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.