[R] using mclapply (multi core apply) to do matrix multiplication

Ernest Adrogué nfdisco at gmail.com
Tue Feb 7 12:21:02 CET 2012


 7-02-2012, 02:31 (-0800); Alaios escriu:
> I would like to thank you Ernest for your answer. I guess that this
> is gonna be faster as right now R only sees one core. In my work
> there is a system with 64 cores and you can see only one working. If
> I understand it right a [m,n][n,k] matrix multiplication can be
> split into rows (from first matrice) and columns (from the second
> matrice) and then combine all the local results of each cpu
> together.
> 
> Would that be too weird for mclapply to handle?

I never used mclapply, but anyway here's a matrix multiplication
function that uses lapply. Because the two lapply's are nested I don't
think you can parallelize the two... I would only make the second one
work with multiple cores

mmult <- function(a, b) {
  a <- as.matrix(a)
  b <- as.matrix(b)
  if (ncol(a) != nrow(b))
    stop('non-conforming matrices')
  out <- lapply(1:ncol(b), function(j)
                lapply(1:nrow(a), function(i) sum(a[i,] * b[,j])))
  array(unlist(out), c(nrow(a), ncol(b)))
}

Also, I'm pretty sure that there are better algorithms.

If you do this it would be interesting if you measured the execution
time of the different alternatives and post the results :)

-- 
Cheers,
Ernest



More information about the R-help mailing list