【问题标题】:Rcpp matrix: loop over rows, one column at a timeRcpp矩阵:循环遍历行,一次一列
【发布时间】:2014-04-10 21:08:57
【问题描述】:

这是我第一次尝试 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];

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

【问题讨论】:

  • 我之前说过,我再说一遍:rcpp-devel 是解决这些问题的更好地方。
  • @DirkEddelbuettel 虽然我知道rcpp-devel 列表可能会更多地接触有使用rcpp 经验的人,但在我看来,stackoverflow 更容易访问。
  • @jbaums:当然,但在所有主要的 rcpp-devel 贡献者中,只有一个在这里看到了问题。提问的眼球减少了……

标签: r rcpp


【解决方案1】:

不能在单个 [ ] 表达式中使用多个索引。这是我所知道的 no 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> 

【讨论】:

  • 漂亮!感谢德克的回复。我会将未来的问题(如果有的话)指向 Rcpp-devel 列表。再次感谢!
  • 您可以使用Am(j,_) 而不是Am.row(j)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 2015-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多