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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With