Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R row-wise multiplication - restyle? [duplicate]

Tags:

r

matrix

If I have, say, an (lots x 5) matrix and a (1 x 5) matrix, is there a better way to multiply them row-wise than this:

> q 
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5

> z
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    6   11   16   21
[2,]    2    7   12   17   22
[3,]    3    8   13   18   23
[4,]    4    9   14   19   24
[5,]    5   10   15   20   25

> t(apply(z,1,function (x) {x*q})) 
     [,1] [,2] [,3] [,4] [,5]
[1,]    1   12   33   64  105
[2,]    2   14   36   68  110
[3,]    3   16   39   72  115
[4,]    4   18   42   76  120
[5,]    5   20   45   80  125

This works but seems bad. Is there a function I'm missing?

like image 740
Carbon Avatar asked Dec 14 '22 17:12

Carbon


1 Answers

Another option is sweep

sweep(z, 2, q, "*")
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1   12   33   64  105
# [2,]    2   14   36   68  110
# [3,]    3   16   39   72  115
# [4,]    4   18   42   76  120
# [5,]    5   20   45   80  125
like image 138
Rich Scriven Avatar answered Jan 07 '23 02:01

Rich Scriven