Rcpp矩阵:循环行,一次一列

Rcpp矩阵:循环行,一次一列,r,rcpp,R,Rcpp,这是我第一次尝试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;

这是我第一次尝试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))
问题显然在这一行,我不知道如何引用矩阵的各个元素

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

如果这是一个愚蠢的新手问题,我道歉。任何暗示都将不胜感激

您不能在一个
[]
表达式中使用多个索引。它是一个C语言的限制,即“强>不<强”> C++矩阵类系统或库我知道克服。因此,请改用
()

修复了这一问题以及您没有将
src
传递给
cxfunction()
的错误,我们得到了以下结果:

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> 
R>src-fun-fun(矩阵(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 sugar提供了一次处理整行或整列的示例,请参见邮件列表存档和小插曲

编辑:为了明确起见,这里使用一个循环和Rcpp sugar的列索引也是一样的:

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> 
R>src-fun-fun(矩阵(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-devel
是回答这些问题的好地方。@Dirkeddebuettel虽然我知道
rcpp-devel
列表可能会让有
rcpp
经验的人接触到更多信息,但我认为stackoverflow是,更容易访问。@jbaums:当然可以,但是在所有关键的rcpp-devel贡献者中,只有一个在这里看到问题。问题的眼球越来越少…太美了!谢谢你的回复,德克。我将把未来的问题(如果有)提交给Rcpp-devel列表。再次感谢!相反,您可以使用
Am.row(j)
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>