Numpy取代for循环计算单个点和多个不同点之间的距离



我正在寻求帮助,通过用numpy代替下面描述的for循环而不使用for循环来加速我的程序。它包括计算从一个点到包含多个点的2d阵列中每个单独点的距离。我在下面添加了代码和注释,使它更清楚。

非常感谢你的帮助。

# some random point
current_point = np.array(423,629)
distances = []
# x and y coordinates of the points saved in np arrays of shape(1,number of points)
# example For three points the xi array could look like: ([231,521,24])
xi = x[indices]
yi = y[indices]
# to get a combined array holding both x and y coordinates. of shape (number of points,2)
x_y = np.vstack((xi, yi)).reshape(-1,2)
# this is the part that i need to speed up. Calculating the distance from the current_point to every point in x_y.
for i in range(xi.shape[0]):
b = np.array(x[i],y[i])
distance = np.linalg.norm(current_point-b)
distances.append(distance)
min_distance = min(distances)

用下面的一行代码替换for循环:

distances = np.linalg.norm(x_y - current_point, axis=1)

你没有正确地堆叠坐标数组,它应该被调换而不是重塑

x_y = np.vstack((xi, yi)).T

则求距离

distances = np.linalg.norm(current_point - x_y, axis= -1)

最新更新