我的目标是找到距离单个点最近的线段(在线段数组中)。 获取 2D 坐标数组之间的点积有效,但使用 3D 坐标会出现以下错误:
*ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 3)*
A = np.array([[1,1,1],[2,2,2]])
B = np.array([[3,3,3], [4,4,4]])
dp = np.dot(A,B)
dp
应该返回 2 个值,
[1,1,1]@[3,3,3]
和 [2,2,2]@[4,4,4]
的点积>/p>
//谢谢大家
这是找到离单个点最近的线段的最终解决方案。
欢迎任何优化。
import numpy as np
import time
#find closest segment to single point
then = time.time()
#random line segment
l1 = np.random.rand(1000000, 3)*10
l2 = np.random.rand(1000000, 3)*10
#single point
p = np.array([5,5,5]) #only single point
#set to origin
line = l2-l1
pv = p-l1
#length of line squared
len_sq = np.sum(line**2, axis = 1) #len_sq = numpy.einsum("ij,ij->i", line, line)
#dot product of 3D vectors with einsum
dot = np.einsum('ij,ij->i',line,pv) #np.sum(line*pv,axis=1)
#percentage of line the pv vector travels in
param = np.array([dot/len_sq])
#param<0 projected point=l1, param>1 pp=l2
clamped_param = np.clip(param,0,1)
#add line fraction to l1 to get projected point
pp = l1+(clamped_param.T*line)
##distance vector between single point and projected point
pp_p = pp-p
#sort by smallest distance between projected point and l1
index_of_mininum_dist = np.sum(pp_p**2, axis = 1).argmin()
print(index_of_mininum_dist)
print("FINISHED IN: ", time.time()-then)
最佳答案
np.dot 仅适用于向量,不适用于矩阵。当传递矩阵时,它期望进行矩阵乘法,但由于传递的维数会失败。
在矢量上它会像你预期的那样工作:
np.dot(A[0,:],B[0,:])
np.dot(A[1,:],B[1,:])
一次完成:
np.sum(A*B,axis=1)
关于python - 具有 3D 向量的两个 numpy 数组的点积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63301019/