[R] multiplying a matrix by a vector

Stefan Evert stefanML at collocations.de
Fri Nov 4 21:52:55 CET 2016


> On 4 Nov 2016, at 17:35, peter dalgaard <pdalgd at gmail.com> wrote:
> 
> Notice though, that Bert loses (or _should_ lose) for larger values of N, since that method involves O(N^3) operations whereas the other two are O(N^2). I am a bit surprised that sweep() is so inefficient even at N=1000.

I also got different results on Mac OS X (with R 3.3.1 and vecLib BLAS):

Unit: milliseconds
                        expr      min       lq     mean   median       uq       max neval
         {     t(y * t(x)) } 18.46369 19.61954 25.77548 21.24242 22.72943  88.03469   100
       {     x %*% diag(y) } 28.12786 29.87109 37.83814 31.59671 32.77839 101.68553   100
 {     sweep(x, 2, y, `*`) } 11.19871 12.76442 21.48670 14.51618 15.70665 100.51444   100

Note that sweep() is considerably _faster_ than the other two methods (which I found quite surprising).

Of course, if you care about speed (and memory efficiency), you could also

	library(wordspace)
	scaleMargins(x, cols=y)

Best,
Stefan



More information about the R-help mailing list