nrowx <- 100000 ncolx <- 100 nrep <- 100 x<-matrix(1, nrowx, ncolx) y<-1 : ncolx m1 <- function (x, y) { x %*% diag (y) } cat("matrix multiplication ", formatC(system.time(gcFirst=TRUE, for (i in 1:nrep) m1(x,y))[1:3], digits=6), "\n") m2 <- function (x, y) { tcrossprod (x, diag(y)) } cat("tcrossprod ", formatC(system.time(gcFirst=TRUE, for (i in 1:nrep) m2(x,y))[1:3], digits=6), "\n") m3 <- function (x, y) { t (y * t(x)) } cat("transposition and reuse ", formatC(system.time(gcFirst=TRUE, for (i in 1:nrep) m3(x,y))[1:3], digits=6), "\n") m4 <- function (x, y) { x * matrix (y, nrowx, ncolx, byrow = TRUE) } cat("elementwise after reshape", formatC(system.time(gcFirst=TRUE, for (i in 1:nrep) m4(x,y))[1:3], digits=6), "\n") m5 <- function (x, y) { sapply (1 : ncolx, function (i) x[, i] * y[i]) } cat("columnwise sapply ", formatC(system.time(gcFirst=TRUE, for (i in 1:nrep) m5(x,y))[1:3], digits=6), "\n") m6 <- function (x, y) { for (i in 1:ncolx) { x[,i] <- x[, i] * y[i] }; return (x) } cat("for loop over columns ", formatC(system.time(gcFirst=TRUE, for (i in 1:nrep) m6(x,y))[1:3], digits=6), "\n")