20

这是我第一次尝试 Rcpp,这个非常简单的问题给我带来了麻烦。我想使用嵌套的 for 循环对矩阵的各个值进行操作,一次一列。我的目标是这样的脚本:

src <- '
    Rcpp::NumericMatrix Am(A);
    int nrows = Am.nrow();
    int ncolumns = Am.ncol();
    for (int i = 0; i < ncolumns; i++){
        for (int j = 1; j < nrows; j++){
            Am[j,i] = Am[j,i] + Am[j-1,i];
        }
    }
    return Am;
'
fun <- cxxfunction(signature(A = "numeric"), body = src, plugin="Rcpp")
fun(matrix(1,4,4))

所需的输出将是这样的:

     [,1] [,2] [,3] [,4]
[1,]    1    1    1    1
[2,]    2    2    2    2
[3,]    3    3    3    3
[4,]    4    4    4    4

问题显然出在这一行,我不知道如何引用矩阵的各个元素。

Am[j,i] = Am[j,i] + Am[j-1,i];

抱歉,如果这是一个愚蠢的新手问题。任何提示将不胜感激!

4

1 回答 1

30

不能在单个[ ]表达式中使用多个索引。这是我所知道的任何C++ 矩阵类系统或库都无法克服的 C 语言限制。所以( )改用。

解决这个问题和你实际上没有传递src给的错误cxxfunction(),我们得到这个:

R> src <- '
+     Rcpp::NumericMatrix Am(A);
+     int nrows = Am.nrow();
+     int ncolumns = Am.ncol();
+     for (int i = 0; i < ncolumns; i++) {
+         for (int j = 1; j < nrows; j++) {
+             Am(j,i) = Am(j,i) + Am(j-1,i);
+         }
+     }
+     return Am;
+ '
R> fun <- cxxfunction(signature(A = "numeric"), body = src, plugin="Rcpp")
R> fun(matrix(1,4,4))
     [,1] [,2] [,3] [,4]
[1,]    1    1    1    1
[2,]    2    2    2    2
[3,]    3    3    3    3
[4,]    4    4    4    4
R> 

最后,请注意 Rcpp 糖有一次处理整行或整列的示例,请参阅邮件列表档案和小插图。

编辑:为了明确起见,这里只使用一个循环和 Rcpp 糖的按列索引是相同的:

R> src <- '
+     Rcpp::NumericMatrix Am(A);
+     int nrows = Am.nrow();
+     for (int j = 1; j < nrows; j++) {
+         Am(j,_) = Am(j,_) + Am(j-1,_);
+     }
+     return Am;
+ '
R> fun <- cxxfunction(signature(A = "numeric"), body = src, plugin="Rcpp")
R> fun(matrix(1,4,4))
     [,1] [,2] [,3] [,4]
[1,]    1    1    1    1
[2,]    2    2    2    2
[3,]    3    3    3    3
[4,]    4    4    4    4
R> 
于 2011-05-08T23:44:51.753 回答