具有相同大小矩阵的多维数组 [英] Multiply multidimensional array with same-sized matrix
问题描述
我想将数组(13x10x10)dfarray = array((1),dim=c(13,10,10))
的每个矩阵(13x10)与相同大小(13x10)mat=matrix(2,13,10)
的另一个矩阵相乘.
I'd like to multiply each matrix (13x10) of an array (13x10x10) dfarray = array((1),dim=c(13,10,10))
with another matrix of the same size (13x10) mat=matrix(2,13,10)
.
I tried the approach posted here, but after dfarray1 <- mat %*% dfarray
(after changing the dimensions as described in the post mentioned) the length changes (1300 vs. 1000) as well as the dimensions of my array.
我觉得自己处在正确的轨道上,但是不知何故,最后一点丢失了.
I feel like I'm on the right track but somehow the last bit is missing.
任何帮助将不胜感激!
Any help would be much appreciated!
推荐答案
尝试此操作以进行逐元素矩阵乘法.
Try this in order to do element-wise matrix multiplication.
#initiate new array with above dimensions
newarray <- array(1, dim=c(13,10,10))
#populate each matrix of the array
for (i in 1:10){
newarray[, , i] <- dfarray[, , i] * mat
}
输出:
> dim(newarray)
[1] 13 10 10
或者按照@DavidArenburg的评论的替代方式:
Or as an alternative way as per @DavidArenburg 's comment just:
newarray[] <- apply(dfarray, 3, `*`, mat)
这篇关于具有相同大小矩阵的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!