简体   繁体   中英

Numpy to replace for loop to calculate distances between a single point and multiple different points individually

I am asking for help to speed up my program by replacing the for loop described below by something with numpy and without a for loop. It involves calculating the distance from a single point to every single point individually in an 2D-array holding multiple points. I have added code and comments below to make it more clear.

Thank you very much for your help.

# 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)

Replace your for loop with this one-liner:

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

you're not properly stacking the coordinate array, it should be transposed not reshaped

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

then to find the distances

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

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