[R] Vectorizing for weighted distance

R. Michael Weylandt michael.weylandt at gmail.com
Thu Nov 17 14:43:15 CET 2011

The fastest is probably to just implement the matrix calculation
directly in R with the %*% operator.

(X1-X2) %*% W %*% (X1-X2)

You don't need to worry about the transposing if you are passing R
vectors X1,X2. If they are 1-d matrices, you might need to.


On Thu, Nov 17, 2011 at 1:30 AM, Sachinthaka Abeywardana
<sachin.abeywardana at gmail.com> wrote:
> Hi All,
> I am trying to convert the following piece of matlab code to R:
> XX1 = sum(w(:,ones(1,N1)).*X1.*X1,1);          #square the elements of X1,
> weight it and repeat this vector N1 times
> XX2 = sum(w(:,ones(1,N2)).*X2.*X2,1);          #square the elements of X2,
> weigh and repeat this vector N2 times
> X1X2 = (w(:,ones(1,N1)).*X1)'*X2;                 #get the weighted
> 'covariance' term
> XX1T = XX1';                                              #transpose
> z = XX1T(:,ones(1,N2)) + XX2(ones(1,N1),:) - 2*X1X2;            #get the
> squared weighted distance
> which is basically doing: z=(X1-X2)' W (X1-X2)
> What would the best way (for SPEED) to do this? or is vectorizing as above
> the best? Any hints, suggestions?
> Thanks,
> Sachin
>        [[alternative HTML version deleted]]
> ______________________________________________
> 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