使用Python生成随机点的欧几里得距离矩阵

3

我编写了一段代码,能够在坐标系中产生特定宽度和长度范围内所需数量的点。我该如何使用欧几里得方法来计算并制成这些点的距离矩阵?

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=', ')

输出是:

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

如何像这个例子一样,使用随机点创建距离矩阵:

Distance Matrix Example

Euclidean Distance formula

非常感谢您的帮助。


1
你可以使用 itertools.combinations(list_of_points, 2) 进行成对分组,并对每一对应用欧几里得距离。使用 numpy 可以更加流畅地进行元素级操作。 - cards
1个回答

0
如果你想使用外部模块,scipy 对于矩阵计算非常高效。
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)

输出

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


1
谢谢伙计。这个解决方案的输出看起来很复杂。我想知道是否可能从0开始编号每个点,以获得像我在问题中添加的图片一样的输出? - user16726326
1
是的,您可以将Numpy数组(mat_dist)转换为Pandas DataFrame(df_mat_dist)。我已经编辑了我的答案;)。 - yannvm
2
谢谢兄弟。你做得像国王一样好 :) - user16726326
1
很高兴为您服务! :) - yannvm
1
兄弟,你能否看一下这个问题?我已经花了几个小时在上面,但是无法得出结论:https://dev59.com/FGwMtIcB2Jgan1zn_Jt5?noredirect=1#comment124010031_70152488 - user16726326

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接