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; 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];
如果这是一个愚蠢的新手问题,我深表歉意。任何提示将不胜感激!
This is my first time trying Rcpp and this very simple problem is giving me trouble. I want to use nested for loops to operate on individual values of a matrix, one column at a time. The script I'm aiming for would look something like this:
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))
The desired output would be this:
[,1] [,2] [,3] [,4]
[1,] 1 1 1 1
[2,] 2 2 2 2
[3,] 3 3 3 3
[4,] 4 4 4 4
The problem is obviously in this line, where I don't know how to refer to individual elements of the matrix.
Am[j,i] = Am[j,i] + Am[j-1,i];
Apologies if this is a stupid newbie question. Any hint would be appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能在单个
[ ]
表达式中使用多个索引。这是我所知道的 C++ 矩阵类系统或库无法克服的 C 语言限制。因此请使用( )
来代替。修复这个问题以及您实际上没有将
src
传递给cxxfunction()
的错误,我们得到:最后,请注意,Rcpp Sugar 有用于处理整行或的示例每次列一次,请参阅邮件列表档案和小插图。
编辑: 明确地说,这里仅使用一个循环和 Rcpp 糖的按列索引:
You cannot use multiple indices in a single
[ ]
expression. It is a C language restriction that no C++ matrix class system or library I know of overcomes. So use( )
instead.Fixing that and the mistake that you didn't actually pass
src
tocxxfunction()
, we get this:Lastly, note that Rcpp sugar has examples for working on entire row or column at a time, see the mailing list archives and vignette.
Edit: Just to be explicit, here is the same using just one loop and the column-wise indexing of Rcpp sugar: