[英]Making an Euclidean Distance Matrix with Random Points in Python
我编写了一个代码,可以在坐标系中的某个宽度和长度范围内产生所需数量的点。 如何计算并制表使用欧几里得方法产生的这些点的距离矩阵?
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 是:
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
如何创建一个带有 rondom 点的距离矩阵,如下例所示:
非常感谢您的帮助。
如果要使用外部模块, scipy
对于矩阵计算非常有效。
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)
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. ]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.