按列滚动总和产品

use*_*169 1 r matrix rcpp

我有两个矩阵,我想将它们相乘,这样得到的矩阵的每个值都是前两个矩阵中相同列的滚动和 - 乘积.

x<-matrix(seq(1:30), ncol=3)
x
      [,1] [,2] [,3]
 [1,]    1   11   21
 [2,]    2   12   22
 [3,]    3   13   23
 [4,]    4   14   24
 [5,]    5   15   25
 [6,]    6   16   26
 [7,]    7   17   27
 [8,]    8   18   28
 [9,]    9   19   29
[10,]   10   20   30
y<-matrix(rep(seq(1:3), 4), ncol=3)/10
y
     [,1] [,2] [,3]
[1,]  0.1  0.2  0.3
[2,]  0.2  0.3  0.1
[3,]  0.3  0.1  0.2
[4,]  0.1  0.2  0.3
Run Code Online (Sandbox Code Playgroud)

所以结果看起来像:

1.8 9.9     20.3
2.5 10.7    21.2
3.2 11.5    22.1
3.9 12.3    23
4.6 13.1    23.9
5.3 13.9    24.8
6   14.7    25.7
Run Code Online (Sandbox Code Playgroud)

在上面的示例输出中,值的10.7计算方法如下:

output[2, 2] = 12 * 0.2 + 13 * 0.3 + 14 * 0.1 + 15 * 0.2
Run Code Online (Sandbox Code Playgroud)

有谁知道怎么做?我一直在玩这个RcppRoll包,但无法得到正确的答案.解决方案越快越好,因为这是需要多次迭代的优化的一部分.

zx8*_*754 5

使用colSums:

t(
  sapply(1:(nrow(x) - nrow(y) + 1), function(i){
    colSums(x[i:((nrow(y)) + i - 1), ] * y)
    })
  )
Run Code Online (Sandbox Code Playgroud)

基于更大的示例数据(在ZheyuanLi的答案中提供),microbenchmark:

Unit: milliseconds
 expr      min       lq     mean   median       uq      max neval cld
   zx 179.8928 186.8033 202.5204 192.3973 199.7500 299.5910   100  a 
   ZL 365.9814 368.3878 391.8303 370.0935 373.4502 489.5045   100   b
Run Code Online (Sandbox Code Playgroud)