Reputation: 3239
What am I doing wrong?
> crossprod(1:3,4:6)
[,1]
[1,] 32
According to this website:http://onlinemschool.com/math/assistance/vector/multiply1/
It should give:
{-3; 6; -3}
See also What is R's crossproduct function?
Upvotes: 5
Views: 6103
Reputation: 8863
> v=c(1,2,3);w=c(4,5,6)
> c(v[2]*w[3]-v[3]*w[2],v[3]*w[1]-v[1]*w[3],v[1]*w[2]-v[2]*w[1])
[1] -3 6 -3
> i1=c(2,3,1);i2=c(3,1,2);v[i1]*w[i2]-v[i2]*w[i1]
[1] -3 6 -3
> pracma::cross(v,w)
[1] -3 6 -3
> sapply(1:length(v),function(i)det(rbind(v,w)[,-i])*(-1)^(i+1))
[1] -3 6 -3
The regular vector cross product operation is only defined in three dimensions, but the last option from the accepted answer is generalized to multiple dimensions. pracma::cross
is implemented the same way as the first option.
Upvotes: 0
Reputation: 7730
You can try expand.grid
expand.grid(LETTERS[1:3],letters[1:3])
Output:
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
Upvotes: 0
Reputation: 71
crossprod computes a Matrix Product. To perform a Cross Product, either write your function, or:
> install.packages("pracma")
> require("pracma")
> cross(v1,v2)
if the first line above does not work, try this:
> install.packages("pracma", repos="https://cran.r-project.org/web/packages/pracma/index.html”)
Upvotes: 5
Reputation: 42649
Here is a generalized cross product:
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)
})
}
For your example:
> xprod(1:3, 4:6)
[1] -3 6 -3
This works for any dimension:
> 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
See https://en.wikipedia.org/wiki/Cross_product
Upvotes: 11
Reputation: 3239
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))
}
Upvotes: 3
Reputation: 2715
crossprod does the following: t(1:3) %*% 4:6
Therefore it is a 1x3 vector times a 3x1 vector --> a scalar
Upvotes: 3