我需要计算两组点之间的所有单位向量。
目前我有这个:
def all_unit_vectors(points_a, points_b):
results = np.zeros((len(points_a) * len(points_b), 3), dtype=np.float32)
count = 0
for pt_a in points_a:
for pt_b in points_b:
results[count] = (pt_a - pt_b)/np.linalg.norm([pt_a - pt_b])
count += 1
return results
in_a = np.array([[51.34, 63.68, 7.98],
[53.16, 63.23, 7.19],
[77.50, 62.55, 4.23],
[79.54, 62.73, 3.61]])
in_b = np.array([[105.58, 61.09, 5.50],
[107.37, 60.66, 6.50],
[130.73, 58.30, 12.33],
[132.32, 58.48, 13.38]])
results = all_unit_vectors(in_a, in_b)
print(results)
(正确)输出:
[[-0.368511 0.01759667 0.01684932]
[-0.3777128 0.02035861 0.00997707]
[-0.47964868 0.03250422 -0.02628129]
[-0.4851439 0.03115273 -0.03235091]
[-0.3551545 0.01449887 0.01145004]
[-0.3644423 0.01727756 0.00463872]
[-0.46762046 0.02971985 -0.03098581]
[-0.4732132 0.02839518 -0.03700341]
[-0.17814296 0.00926242 -0.00805704]
[-0.18821244 0.01190899 -0.01430339]
[-0.3044056 0.02430441 -0.04632135]
[-0.31113514 0.0230996 -0.05193153]
[-0.16408844 0.0103343 -0.01190965]
[-0.1741932 0.01295652 -0.01808905]
[-0.29113463 0.02519489 -0.04959355]
[-0.29793915 0.02399093 -0.05515092]]
循环all_unit_vectors()
可以矢量化吗?
norm
是根据平方和的平方根计算的,您可以norm
按以下方式实现自己的计算,然后通过广播对解决方案进行矢量化处理:
diff = (in_a[:, None] - in_b).reshape(-1, 3)
norm = ((in_a[:, None] ** 2 + in_b ** 2).sum(2) ** 0.5).reshape(-1, 1)
diff / norm
给出:
[[-0.36851098 0.01759667 0.01684932]
[-0.3777128 0.02035861 0.00997706]
[-0.47964868 0.03250422 -0.02628129]
[-0.4851439 0.03115273 -0.03235091]
[-0.35515452 0.01449887 0.01145004]
[-0.36444229 0.01727756 0.00463872]
[-0.46762047 0.02971985 -0.03098581]
[-0.4732132 0.02839518 -0.03700341]
[-0.17814297 0.00926242 -0.00805704]
[-0.18821243 0.01190899 -0.01430339]
[-0.30440561 0.02430441 -0.04632135]
[-0.31113513 0.0230996 -0.05193153]
[-0.16408845 0.0103343 -0.01190965]
[-0.1741932 0.01295652 -0.01808905]
[-0.29113461 0.02519489 -0.04959355]
[-0.29793917 0.02399093 -0.05515092]]
播放。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句