Skip to content
Prev 264866 / 398502 Next

vectors cross-product V1 x V2

RSiteSearch("cross product")
library(pracma)
?cross

Speed is usually desired in the context of many similar computations, and is 
normally achieved in R by vectorizing computation, so storing the large 
number of 3d vectors together in a structure like a Nx3 matrix so the code 
can be vectorized is the logical approach.  The cross() function takes 
inputs in this form, but the current implementation (0.6-3) then fails to 
take advantage of that storage since it iterates with a for loop. A better 
core implementation of cross() might be:

vcrossp <- function( a, b ) {
   result <- matrix( NA, nrow( a ), 3 )
   result[,1] <- a[,2] * b[,3] - a[,3] * b[,2]
   result[,2] <- a[,3] * b[,1] - a[,1] * b[,3]
   result[,3] <- a[,1] * b[,2] - a[,2] * b[,1]
   result
}

which is about 20 times faster than cross() on my machine.
On 07/08/2011 05:52 AM, Eik Vettorazzi wrote: