[R] approaches tpmatrix multiplication of each layer of 3-d array with different matrix
Ranjan Maitra
maitra.mbox.ignored at inbox.com
Fri Jul 10 15:23:49 CEST 2015
Dear friends,
I have two 3-d arrays of appropriate dimensions. I want to postmultiply the 2-D matrix layers of the first with the 2-D matrix layers of the second. Can I do this easily in R avoiding loops?
As an example:
--- begin R code ---
AA <- array(1:60, dim = c(5500,44,33))
BB <- array(1:60, dim = c(44,44,33))
arraymatprod <- function(A, B) {
EE <- array(dim=dim(A));
for (i in 1:3) EE[,,i] <- A[,,i] %*% B[,,i]
EE
}
system.time(arraymatprod(AA, BB))
--- end R code ---
So, is there a way to do this without the loop?
Of course, I could abind the arrays and then use apply with an appropriate function which would be as follows:
--- begin R code ---
arraymatrixproduct <- function(A, B) {
require(abind)
dA <- dim(A)[1]
AB <- abind(A, B, along = 1)
array(apply(X = AB, MARGIN = 3, FUN = (function(mat) ((mat[1:dA, ] %*% mat[(dA+1):(dim(AB)[1]),])))), dim = dim(A))
}
system.time(arraymatrixproduct(AA, BB))
--- end R code ---
However, this turns out to be slower -- perhaps because of the use of abind and filling the array inside the function.
I just wanted suggestions to get this operation done more efficiently.
Many thanks and best wishes,
Ranjan
____________________________________________________________
Publish your photos in seconds for FREE
TRY IM TOOLPACK at http://www.imtoolpack.com/default.aspx?rc=if4
More information about the R-help
mailing list