Automatic multiplication between vector and matrix

前端 未结 4 978
挽巷
挽巷 2021-01-19 21:52

I have this R code:

> coef
[1] 1.5 2.4 3.9 4.4
> y
     [,1] [,2] [,3] [,4]
[1,]    1    2   12   45
[2,]    5    6    7    8
[3,]    9   10    2   12
         


        
4条回答
  •  北海茫月
    2021-01-19 22:32

    A late entry:

    coef[col(y)]*y
    

    On my system, this is the fastest.

                                          test replications elapsed relative
    6                         coef[col(y)] * y        10000   0.068    1.000
    5 scale(y, center = FALSE, scale = 1/coef)        10000   0.640    9.412
    4                   sweep(y, 2, coef, "*")        10000   0.535    7.868
    3                t(apply(y, 1, "*", coef))        10000   0.837   12.309
    1                           t(t(y) * coef)        10000   0.176    2.588
    2                         y %*% diag(coef)        10000   0.187    2.750
    

提交回复
热议问题