Does R optimise the order of matrix multiplications? -
if multiplying 3 matrices together, abc. depending on size of matrices may more efficient perform either (ab)c or a(bc). if evaluate:
a %*% b %*% c
will optimised in anyway?
thanks colonel beauvel setting me on right path - test it. using example wikipedia , scaling suitably:
> mult <- 100 > ar <- 10 * mult > ac <- 30 * mult > br <- 30 * mult > bc <- 5 * mult > cr <- 5 * mult > cc <- 60 * mult > > <- matrix(rnorm(ar * ac), ar, ac) > b <- matrix(rnorm(br * bc), br, bc) > c <- matrix(rnorm(cr * cc), cr, cc) > > system.time({ (a %*% b) %*% c }) user system elapsed 3.01 0.00 3.01 > system.time({ %*% (b %*% c) }) user system elapsed 25.34 0.03 25.37 > system.time({ %*% b %*% c }) user system elapsed 2.98 0.00 2.98 > system.time({ t(c) %*% t(b) %*% t(a) }) user system elapsed 25.61 0.03 25.64
incidently - r evaluates left right.
Comments
Post a Comment