[R] vectors cross-product V1 x V2
Jeff Newmiller
jdnewmil at dcn.davis.ca.us
Fri Jul 8 16:56:35 CEST 2011
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:
> Hi,
> how about this:
>
> mm<-cbind(V1,V2)
> xy<-sapply(1:3,function(x)det(mm[-x,])*(2*(x%%2)-1))
>
> #some checks
> all.equal(0,as.vector(xy%*%V1))
> all.equal(0,as.vector(xy%*%V2))
>
>
> Am 08.07.2011 08:27, schrieb Bai:
>> Hi, everyone,
>>
>> I need an efficient way to do vectors cross product in R.
>>
>> Set vectors,
>> V1 = ai + bj + ck
>> V2 = di + ej + fk
>>
>> then the cross product is
>> V1 x V2 = (bf - ce) i + (cd - af) j + (ae - bd) k
>>
>>
>> As shown here ( http://en.wikipedia.org/wiki/Cross_product ).
>>
>> Thanks.
>>
>> Best,
>> Bai
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list