arrays - Sum of matrices in 3-dimensional object of variable dimesions without looping -
arrays - Sum of matrices in 3-dimensional object of variable dimesions without looping -
i have 3-dimensional object in r, contains n square matrices. example:
myobject[,,1] # returns square matrix myobject[,,2] # returns square matrix of same size ...
all matrices within object of same size. i'd add together matrices together, without loop. simple plenty if know how many matrices in object. example:
matrixsum <- myobject[,,1] + myobject[,,2] + myobject[,,3]
the problem is, need several one thousand such objects, , there variable number of matrices in each object. there way can without loop? in sense, i'd seek "vectorize" summation.
thanks!
the convient, not fastest, utilize apply
:
matrixsum <- apply(myobject, c(1,2), sum)
example
myobject <- array(c(1,2,3),dim = c(3,4,3)) myobject , , 1 [,1] [,2] [,3] [,4] [1,] 1 1 1 1 [2,] 2 2 2 2 [3,] 3 3 3 3 , , 2 [,1] [,2] [,3] [,4] [1,] 1 1 1 1 [2,] 2 2 2 2 [3,] 3 3 3 3 , , 3 [,1] [,2] [,3] [,4] [1,] 1 1 1 1 [2,] 2 2 2 2 [3,] 3 3 3 3 apply(myobject, c(1,2), sum) [,1] [,2] [,3] [,4] [1,] 3 3 3 3 [2,] 6 6 6 6 [3,] 9 9 9 9
addition:
using rowsums
should must faster:
rowsums(myobject, dims = 2) [,1] [,2] [,3] [,4] [1,] 3 3 3 3 [2,] 6 6 6 6 [3,] 9 9 9 9
arrays r performance matrix vectorization
Comments
Post a Comment