Efficient row wise matrix operation in R

Viewed 181

I have 2 matrices M1, M2. For each row in M1, I want to find the maximum value of the product of that row in M1 and each row in M2.

I have tried the following implementation which produces the result I want.

set.seed(1)
st_time = Sys.time()
M1 = matrix(runif(1000*10), nrow=1000, ncol=10)
M2 = matrix(runif(10000*10), nrow=10000, ncol=10)

score = apply(M1, 1, function(x){
  w = M2 %*% diag(x)
  row_max = apply(w, 1, max)
  return(row_max)
})
required_output = t(score)
Sys.time() - st_time

This takes 16 seconds on my machine. Is there a faster implementation? Thanks!

2 Answers
Related