[R] vectors cross-product V1 x V2
Bai
bailhcn at gmail.com
Sat Jul 9 02:34:36 CEST 2011
Thank you all.
I do have two huge matrix like M1[x,y,z,3] x M2[x,y,z,3].
I'll try it.
Best,
Bai
On Fri, Jul 8, 2011 at 11:56 PM, Jeff Newmiller
<jdnewmil at dcn.davis.ca.us> wrote:
> 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