答案 0 :(得分:2)
您可以使用aperm
并利用矢量化。你必须说明"普通"尺寸(即X
和C
中包含的尺寸),置换X
并相乘。类似的东西:
#declare which are the dimensions in X common to C
commonDims<-c(3,4)
#the other dimensions are the "uncommon" ones
uncommonDims<-setdiff(seq_along(dims),commonDims)
#then you can get the sum
sum(as.vector(aperm(X,c(commonDims,uncommonDims)))*as.vector(C))
我们使用for
循环获得的结果测试上面的结果:
set.seed(456)
dims<-c(5,6,2,3,8)
commonDims<-c(3,4)
uncommonDims<-setdiff(seq_along(dims),commonDims)
C<-array(runif(prod(dims[commonDims])),dims[commonDims])
X<-array(runif(prod(dims)),dims)
sum(as.vector(aperm(X,c(commonDims,uncommonDims)))*as.vector(C))
#[1] 371.3749
#Calculation through loops
rsum<-0
for (i in 1:dims[1])
for (j in 1:dims[2])
for (k in 1:dims[3])
for (r in 1:dims[4])
for (t in 1:dims[5]) rsum<-rsum + X[i,j,k,r,t]*C[k,r]
rsum
#[1] 371.3749