连续2D矢量之间的角度

时间:2016-02-27 16:14:50

标签: r math vector

我在计算连续2D矢量之间的顺时针角度时遇到了一些麻烦。当我在一个情节上用眼睛比较时,我的计算角度似乎不正确。以下是我在R的过程。

如有必要,请安装并启用“循环”包:

install.packages('circular')
library(circular)

生成2D坐标的小数据框:

functest <- data.frame(x=c(2,8,4,9,10,7),y=c(6,8,2,5,1,4))

绘制要参考的点:

windows(height=8,width=8)
par(pty="s")
plot(functest, main = "Circular Functions Test")
## draw arrows from point to point :
s <- seq(length(functest$x)-1)  # one shorter than data
arrows(functest$x[s], functest$y[s], functest$x[s+1], functest$y[s+1], col = 1:3)

创建一个计算两个向量之间角度的函数:

angle <- function(m)
{   # m is a matrix
  dot.prod <- crossprod(m[, 1], m[, 2])
  norm.x <- norm(m[, 1], type="2")
  norm.y <- norm(m[, 2], type="2")
  theta <- acos(dot.prod / (norm.x * norm.y))
  as.numeric(theta) # returns the angle in radians
}

生成以度为单位的罗盘角矢量(顺时针旋转):

functest_matrix <- cbind(x = functest$x,y = functest$y)
moves <- apply(functest_matrix, 2, diff)
tst <- lapply(seq(nrow(moves) - 1), function(idx) moves[c(idx, idx + 1), ])
functest_angles <- vapply(tst, angle, numeric(1))
functest_object <- circular(functest_angles, type="angles", units="radians", zero=0, rotation = "counter")
functest_convert <- conversion.circular(functest_object, type = "angles", units = "degrees", rotation = "clock", zero = pi/2)
functest_compass <- lapply(functest_convert, function(x) {if (x < 0) x+360 else x}) # converts any negative rotations to positive

当我尝试将弧度的“正常”逆时针角度转换为以度为单位的顺时针罗盘角度时,我怀疑在我的最后三行代码中可能出现了错误。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

不知道R但是看到你使用标量积来计算矢量之间的角度。

请注意,结果角度不是指向的 - 既不是顺时针也不是逆时针(考虑标量乘积对矢量交换不敏感)。

如果你真的需要定向角度(旋转第一个矢量以使其与第二个矢量共线所需的角度),你必须应用ArcTan2atan2)方法
(结果范围通常为-Pi..Pi

Theta = ArcTan2(CrossProduct(v1,v2), DotProduct(v1,v2))

答案 1 :(得分:0)

这条线对我来说毫无意义:

dot.prod <- crossprod(m[, 1], m[, 2])

将两个向量的叉积分配给名为dot product的变量。

我没有阅读其余的代码,但这些是两个非常不同的东西。

点积产生标量值;叉积产生与另外两个正交的矢量。

您确定您的命名并不反映对这两项操作的误解吗?它可以解释你为什么遇到麻烦。

您可以使用点积来获得任意两个向量之间的角度。为什么你认为你需要在那种方法中遇到麻烦?