gpt4 book ai didi

R - 计算向量的叉积(物理)

转载 作者:行者123 更新时间:2023-12-04 10:08:17 26 4
gpt4 key购买 nike

我究竟做错了什么?

> 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com