我在寻找有效的替代方法来计算二维向量之间的余弦角。你对这个问题的见解会很有帮助的。在
vectors
是存储向量的二维数组。vectors
数组的形状是(N, 2)
,其中N
是向量的数目。vectors[:, 0]
有x分量,vectors[:, 1]
有y分量。在
我要找出vectors
中所有向量之间的夹角。例如,如果vectors
中有三个向量A,B,C,我需要找到A and B
,B and C
,和A and C
之间的夹角。在
我已经实现了它,想知道其他方法。在
vectors = np.array([[1, 3], [2, 4], [3, 5]])
vec_x = vectors[:, 0]
vec_y = vectors[:, 1]
a1 = np.ones([vec_x.shape[0], vec_x.shape[0]]) * vec_x
a2 = np.ones([vec_x.shape[0], vec_x.shape[0]]) * vec_y
a1b1 = a1 * a1.T
a2b2 = a2 * a2.T
mask = np.triu_indices(a1b1.shape[0], 0) # We are interested in lower triangular matrix
a1b1[mask] = 0
a2b2[mask] = 0
numer = a1b1 + a2b2
denom = np.ones([vec_x.shape[0], vec_x.shape[0]]) * np.sqrt(np.square(a1) + np.square(a2))
denom = denom * denom.T
denom[mask] = 0
eps = 1e-7
dot_res = np.rad2deg(np.arccos(np.divide(numer, denom + eps)))
dot_res[mask] = 0
print(dot_res)
有没有其他方法可以提高效率?
我们能在某种程度上提高当前版本的速度吗?
使用^{} :
相关问题 更多 >
编程相关推荐