Created
September 4, 2012 18:27
-
-
Save grej/3624583 to your computer and use it in GitHub Desktop.
R function to generate a vector cross product
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)
}
}