我觉得愚蠢的问,但R的crossprod功能对于矢量输入的意图是什么 ?我想计算欧几里得空间中两个向量的交叉积,并错误地尝试使用crossprod.
矢量叉积的一个定义是N = |A|*|B|*sin(theta)θ是两个矢量之间的角度.(方向N垂直于AB平面).另一种计算方法是 N = Ax*By - Ay*Bx.
base::crossprod显然不做这个计算,实际上产生两个输入的矢量点积sum(Ax*Bx, Ay*By).
所以,我可以轻松编写自己的vectorxprod(A,B)函数,但我无法弄清楚crossprod一般情况下做了什么.
vin*_*ief 21
根据R中的帮助函数:crossprod(X,Y)= t(X)%*%Y是比表达式本身更快的实现.它是两个矩阵的函数,如果你有两个向量对应于点积.
Chi*_*ogg 10
这是一个简短的代码片段,只要交叉产品有意义就可以使用: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)
Run Code Online (Sandbox Code Playgroud)
让我们看一下我在网上找到的随机例子:
> CrossProduct3D(c(3, -3, 1), c(4, 9, 2)) == c(-15, -2, 39)
[1] TRUE TRUE TRUE
Run Code Online (Sandbox Code Playgroud)
看起来不错!
缺点是数字'3'被硬编码数次.实际上,这并不是一件坏事,因为它突出了矢量交叉产品纯粹是3D构造的事实.就个人而言,我建议完全抛弃交叉产品并改为学习几何代数.:)
帮助?crossprod里解释的很清楚。以线性回归为例,对于一个模型,y = XB + e您想要找到的转置和X'X的乘积。为此,一个简单的调用就足够了:is the same as is the same as 。此外,还可用于求两个向量的点积。XXcrossprod(X)crossprod(X,X)t(X) %*% Xcrossprod
| 归档时间: |
|
| 查看次数: |
27380 次 |
| 最近记录: |