How to divide each row of a matrix by elements of a vector in R

Viewed 85861

I would like to divide each row of a matrix by a fixed vector. For example

mat<-matrix(1,ncol=2,nrow=2,TRUE)
dev<-c(5,10)

Giving mat/dev divides each column by dev.

     [,1] [,2]
[1,]  0.2  0.2
[2,]  0.1  0.1

However, I would like to have this as a result, i.e. do the operation row-wise :

rbind(mat[1,]/dev, mat[2,]/dev)

     [,1] [,2]
[1,]  0.2  0.1
[2,]  0.2  0.1

Is there an explicit command to get there?

3 Answers

Not only faster than the fastest base method (using matrix multiplication, see @G. Grothendieck's answer) but also more readable is the use of rray package that allows numpy-like broadcasting for division with its %b/% operator:

mat %b/% matrix(dev, nrow = 1)

#install.packages("rray")
library(rray)

set.seed(84789)
mat <- matrix(runif(1e6), nrow = 1e5)
dev <- runif(10)

bench::mark(rray = {ret <- mat %b/% matrix(dev, nrow = 1); attr(ret, "dimnames") <- NULL; ret}, 
            matmult = mat %*% diag(1/dev)
)
#> # A tibble: 2 x 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 rray         8.24ms   8.82ms     108.     7.67MB     46.4
#> 2 matmult     11.17ms  12.01ms      77.6    7.66MB     13.9
Related