简体   繁体   中英

Making an Euclidean Distance Matrix with Random Points in Python

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:

距离矩阵示例

欧几里得距离公式

Thanks a lot for the help.

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

import random
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')
print(mat_dist)

Output

Type the npoints:4
Enter the Width you want:10
Enter the Height you want:10
(0.51, 2.80), (5.93, 9.46), (6.70, 4.34), (6.63, 6.53)
[[0.         8.58570336 6.37178369 7.16973499]
 [8.58570336 0.         5.17134317 3.00545614]
 [6.37178369 5.17134317 0.         2.19288637]
 [7.16973499 3.00545614 2.19288637 0.        ]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM