Home > Software design >  Making an Euclidean Distance Matrix with Random Points in Python
Making an Euclidean Distance Matrix with Random Points in Python

Time:11-29

I wrote a code that produces the desired number of points in a certain width and length range in the coordinate system. How can I calculate and tabulate the distance matrix of these points I produced using the Euclidean method?

import random

npoints = int(input("Type the npoints:"))
width = float(input("Enter the Width you want:"))
height = float(input("Enter the Height you want:"))

sample = []
for _ in range(npoints):
    sample.append((width * random.random(), height * random.random()))
print(*[f"({w:.2f}, {h:.2f})" for w, h in sample], sep=', ')

Output is:

Type the npoints:4
Enter the Width you want:10
Enter the Height you want:10
(8.52, 3.73), (9.69, 6.87), (8.20, 6.14), (4.18, 0.76)

Process finished with exit code 0

How can I create a distance matrix with rondom points like this example:

Distance Matrix Example

Euclidean Distance formula

Thanks a lot for the help.

CodePudding user response:

If you want to use external modules, scipy is very efficient for matrix calculations.

import random
import pandas as pd
from scipy.spatial import distance

npoints = int(input("Type the npoints:"))
width = float(input("Enter the Width you want:"))
height = float(input("Enter the Height you want:"))

sample = []
for _ in range(npoints):
    sample.append((width * random.random(), height * random.random()))
print(*[f"({w:.2f}, {h:.2f})" for w, h in sample], sep=', ')

#Create a matrix from these points
mat_dist = distance.cdist(sample, sample, 'euclidean')
df_mat_dist = pd.DataFrame(mat_dist)
print(df_mat_dist)

Output

Type the npoints:4
Enter the Width you want:10
Enter the Height you want:10
(8.89, 8.85), (9.00, 9.43), (9.67, 9.45), (3.96, 5.68)
          0         1         2         3
0  0.000000  0.584322  0.985072  5.856736
1  0.584322  0.000000  0.669935  6.277323
2  0.985072  0.669935  0.000000  6.839240
3  5.856736  6.277323  6.839240  0.000000

  • Related