Recycling can make it faster but you recycle within columns, not across, so just transpose and transpose back.
t( t(mat) * v )
This should be faster than sweep
or %*%
.
microbenchmark(mat %*% diag(v),sweep(mat, 2, v, FUN = "*"), t(t(mat)*v))
Unit: milliseconds
expr min lq median uq max neval
%*% 150.47301 152.16306 153.17379 161.75416 281.3315 100
sweep 35.94029 42.67210 45.53666 48.07468 168.3728 100
t(t(mat) * v) 16.50813 23.41549 26.31602 29.44008 160.1651 100
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…