我有代码
import numpy as np
import math
pos = np.array([[ 1.72, 2.56],
[ 0.24, 5.67],
[ -1.24, 5.45],
[ -3.17, -0.23],
[ 1.17, -1.23],
[ 1.12, 1.08]])
ref = np.array([1.22, 1.18])
# Insert your solution below
d1 = math.sqrt((pos[0,0]-ref[0])**2 + (pos[0,1]-ref[1])**2)
d2 = math.sqrt((pos[1,0]-ref[0])**2 + (pos[1,1]-ref[1])**2)
d3 = math.sqrt((pos[2,0]-ref[0])**2 + (pos[2,1]-ref[1])**2)
d4 = math.sqrt((pos[3,0]-ref[0])**2 + (pos[3,1]-ref[1])**2)
d5 = math.sqrt((pos[4,0]-ref[0])**2 + (pos[4,1]-ref[1])**2)
d6 = math.sqrt((pos[5,0]-ref[0])**2 + (pos[5,1]-ref[1])**2)
预期的答案是
# [ 1.468, 4.596, 4.928 , 4.611, 2.410, 0.141 ]
是否可以使我的解决方案更加高效和简短,最好不使用 for 循环。 谢谢:D
最佳答案
你的方程实际上是pos
和ref
之间的欧几里德距离。您可以使用 np.linalg.norm
dist_arr = np.linalg.norm(pos-ref, axis=1)
Out[14]:
array([1.46778745, 4.59570452, 4.9279306 , 4.61087844, 2.41051862,
0.14142136])
关于arrays - 不使用 for 循环的数组广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64761341/