首页 文章

R的交叉产品功能是什么?

提问于
浏览
25

我觉得很愚蠢,但R的 crossprod 函数对矢量输入的意图是什么?我想计算欧几里德空间中两个向量的交叉积,并错误地尝试使用 crossprod .
矢量叉积的一个定义是 N = |A|*|B|*sin(theta) ,其中θ是两个矢量之间的角度 . ( N 的方向垂直于A-B平面) . 另一种计算方法是 N = Ax*By - Ay*Bx .
base::crossprod 显然不做这个计算,实际上产生了两个输入的矢量点积 sum(Ax*Bx, Ay*By) .

所以,我可以轻松编写自己的 vectorxprod(A,B) 函数,但我无法弄清 crossprod 一般在做什么 .

另见R - Compute Cross Product of Vectors (Physics)

5 回答

  • 10

    根据R中的帮助函数:crossprod(X,Y)= t(X)%*%Y是一个比表达式本身更快的实现 . 它是两个矩阵的函数,如果你有两个向量对应于点积 .

  • 3

    这是一个简短的代码片段,只要交叉产品有意义就可以使用:3D版本返回一个向量,2D版本返回一个标量 . 如果您只是想要简单的代码,无需引入外部库即可提供正确的答案,这就是您所需要的 .

    # Compute the vector cross product between x and y, and return the components
    # indexed by i.
    CrossProduct3D <- function(x, y, i=1:3) {
      # Project inputs into 3D, since the cross product only makes sense in 3D.
      To3D <- function(x) head(c(x, rep(0, 3)), 3)
      x <- To3D(x)
      y <- To3D(y)
    
      # Indices should be treated cyclically (i.e., index 4 is "really" index 1, and
      # so on).  Index3D() lets us do that using R's convention of 1-based (rather
      # than 0-based) arrays.
      Index3D <- function(i) (i - 1) %% 3 + 1
    
      # The i'th component of the cross product is:
      # (x[i + 1] * y[i + 2]) - (x[i + 2] * y[i + 1])
      # as long as we treat the indices cyclically.
      return (x[Index3D(i + 1)] * y[Index3D(i + 2)] -
              x[Index3D(i + 2)] * y[Index3D(i + 1)])
    }
    
    CrossProduct2D <- function(x, y) CrossProduct3D(x, y, i=3)
    

    有效吗?

    我们来看看a random example I found online

    > CrossProduct3D(c(3, -3, 1), c(4, 9, 2)) == c(-15, -2, 39)
    [1] TRUE TRUE TRUE
    

    看起来不错!

    为什么这比以前的答案更好?

    • 它's 3D (Carl' s仅为2D) .

    • 这很简单,也很惯用 .

    • 评论和格式很好;因此,易于理解

    缺点是数字'3'已经多次硬编码 . 实际上,这并不是一件坏事,因为它突出了矢量交叉产品纯粹是3D构造的事实 . 就个人而言,我建议改为ditching cross products entirelylearning Geometric Algebra . :)

  • 17

    帮助 ?crossprod 非常清楚地解释了它 . 以线性回归为例,对于模型 y = XB + e ,您要查找 X'XX 转置和 X 的乘积 . 为此,一个简单的调用就足够了: crossprod(X)crossprod(X,X) 相同,与 t(X) %*% X 相同 . 此外, crossprod 可用于查找两个向量的点积 .

  • 0

    为了回应@Bryan Hanson的要求,这里有一些Q&D代码来计算平面中两个向量的向量叉积 . 计算一般的3空间矢量交叉产品或扩展到N空间有点麻烦 . 如果你需要那些,你将不得不去维基百科:-) .

    crossvec <- function(x,y){
    if(length(x)!=2 |length(y)!=2) stop('bad vectors')
     cv <-  x[1]*y[2]-x[2]*y[1]
    return(invisible(cv))
    }
    
  • 2

    这是3D矢量的简约实现:

    vector.cross <- function(a, b) {
        if(length(a)!=3 || length(b)!=3){
            stop("Cross product is only defined for 3D vectors.");
        }
        i1 <- c(2,3,1)
        i2 <- c(3,1,2)
        return (a[i1]*b[i2] - a[i2]*b[i1])
    }
    

    如果你想获得2D矢量 uv 的标量"cross product",你可以做

    vector.cross(c(u,0),c(v,0))[3]
    

相关问题