我究竟做错了什么?
> crossprod(1:3,4:6)
[,1]
[1,] 32
根据此网站:http://onlinemschool.com/math/assistance/vector/multiply1/
它应该给出:
{-3; 6; -3}
另请参阅What is R's crossproduct function?
最佳答案
这是广义的叉积:
xprod <- function(...) {
args <- list(...)
# Check for valid arguments
if (length(args) == 0) {
stop("No data supplied")
}
len <- unique(sapply(args, FUN=length))
if (length(len) > 1) {
stop("All vectors must be the same length")
}
if (len != length(args) + 1) {
stop("Must supply N-1 vectors of length N")
}
# Compute generalized cross product by taking the determinant of sub-matricies
m <- do.call(rbind, args)
sapply(seq(len),
FUN=function(i) {
det(m[,-i,drop=FALSE]) * (-1)^(i+1)
})
}
例如:
> xprod(1:3, 4:6)
[1] -3 6 -3
这适用于任何尺寸:
> xprod(c(0,1)) # 2d
[1] 1 0
> xprod(c(1,0,0), c(0,1,0)) # 3d
[1] 0 0 1
> xprod(c(1,0,0,0), c(0,1,0,0), c(0,0,1,0)) # 4d
[1] 0 0 0 -1
参见https://en.wikipedia.org/wiki/Cross_product
关于R-计算向量的叉积(物理),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36798301/