R - 计算向量的叉积(物理)
R - Compute Cross Product of Vectors (Physics)
我做错了什么?
> crossprod(1:3,4:6)
[,1]
[1,] 32
根据本网站:http://onlinemschool.com/math/assistance/vector/multiply1/
它应该给出:
{-3; 6; -3}
另见 What is R's crossproduct function?
crossprod 执行以下操作:t(1:3) %*% 4:6
因此它是一个 1x3 向量乘以一个 3x1 向量 --> 一个标量
crossProduct <- function(ab,ac){
abci = ab[2] * ac[3] - ac[2] * ab[3];
abcj = ac[1] * ab[3] - ab[1] * ac[3];
abck = ab[1] * ac[2] - ac[1] * ab[2];
return (c(abci, abcj, abck))
}
这是一个广义叉积:
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
crossprod 计算 Matrix Product. To perform a Cross Product,要么编写您的函数,要么:
> install.packages("pracma")
> require("pracma")
> cross(v1,v2)
如果上面的第一行不起作用,试试这个:
> install.packages("pracma", repos="https://cran.r-project.org/web/packages/pracma/index.html”)
你可以试试expand.grid
expand.grid(LETTERS[1:3],letters[1:3])
输出:
Var1 Var2
1 A a
2 B a
3 C a
4 A b
5 B b
6 C b
7 A c
8 B c
9 C c
我做错了什么?
> crossprod(1:3,4:6)
[,1]
[1,] 32
根据本网站:http://onlinemschool.com/math/assistance/vector/multiply1/
它应该给出:
{-3; 6; -3}
另见 What is R's crossproduct function?
crossprod 执行以下操作:t(1:3) %*% 4:6
因此它是一个 1x3 向量乘以一个 3x1 向量 --> 一个标量
crossProduct <- function(ab,ac){
abci = ab[2] * ac[3] - ac[2] * ab[3];
abcj = ac[1] * ab[3] - ab[1] * ac[3];
abck = ab[1] * ac[2] - ac[1] * ab[2];
return (c(abci, abcj, abck))
}
这是一个广义叉积:
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
crossprod 计算 Matrix Product. To perform a Cross Product,要么编写您的函数,要么:
> install.packages("pracma")
> require("pracma")
> cross(v1,v2)
如果上面的第一行不起作用,试试这个:
> install.packages("pracma", repos="https://cran.r-project.org/web/packages/pracma/index.html”)
你可以试试expand.grid
expand.grid(LETTERS[1:3],letters[1:3])
输出:
Var1 Var2
1 A a
2 B a
3 C a
4 A b
5 B b
6 C b
7 A c
8 B c
9 C c