Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Compute Cross Product of Vectors (Physics)

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?

like image 459
Kevin Avatar asked Apr 22 '16 15:04

Kevin


2 Answers

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

like image 89
Matthew Lundberg Avatar answered Nov 12 '22 10:11

Matthew Lundberg


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”)
like image 5
Tommy_Emmons Avatar answered Nov 12 '22 11:11

Tommy_Emmons