Skip to content

Instantly share code, notes, and snippets.

@grej
Created September 4, 2012 18:27
Show Gist options
  • Save grej/3624583 to your computer and use it in GitHub Desktop.
Save grej/3624583 to your computer and use it in GitHub Desktop.
R function to generate a vector cross product
# takes either a vector or one-dimensional matrix as inputs a&b
xprod <- function(a,b) {
if(length(a)==3 && length(b)==3){
getDet <- function(w,x,y,z) {
return(det(matrix(c(w,x,y,z),ncol=2)))
}
return(c(getDet(a[2],b[2],a[3],b[3]),-getDet(a[1],b[1],a[3],b[3]),getDet(a[1],b[1],a[2],b[2])))
}else{
return(FALSE)
}
}
# below implementation will creates a %X% operator for the vector cross product
"%X%" <- function(a,b) {
if(length(a)==3 && length(b)==3){
getDet <- function(w,x,y,z) {
return(det(matrix(c(w,x,y,z),ncol=2)))
}
return(c(getDet(a[2],b[2],a[3],b[3]),-getDet(a[1],b[1],a[3],b[3]),getDet(a[1],b[1],a[2],b[2])))
}else{
return(FALSE)
}
}
@grej
Copy link
Author

grej commented Sep 4, 2012

below implementation will allow use of custom operator u %X% v to produce vector cross product

"%X%" <- function(a,b) {
if(length(a)==3 && length(b)==3){
getDet <- function(w,x,y,z) {
return(det(matrix(c(w,x,y,z),ncol=2)))
}
return(c(getDet(a[2],b[2],a[3],b[3]),-getDet(a[1],b[1],a[3],b[3]),getDet(a[1],b[1],a[2],b[2])))
}else{
return(FALSE)
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment