Rcpp 矩阵:遍历行,一次一列 [英] Rcpp matrix: loop over rows, one column at a time
问题描述
这是我第一次尝试 Rcpp,这个非常简单的问题给我带来了麻烦.我想使用嵌套的 for 循环对矩阵的单个值进行操作,一次一列.我的目标脚本如下所示:
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))
所需的输出是这样的:
[,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!
推荐答案
您不能在单个 [ ]
表达式中使用多个索引.这是我所知道的没有 C++ 矩阵类系统或库可以克服的 C 语言限制.所以用 ( )
代替.
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.
解决这个问题以及您实际上没有将 src
传递给 cxxfunction()
的错误,我们得到了:
Fixing that and the mistake that you didn't actually pass src
to cxxfunction()
, we get this:
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 Sugar 有一次处理整行或整列的示例,请参阅邮件列表档案和小插图.
Lastly, note that Rcpp sugar has examples for working on entire row or column at a time, see the mailing list archives and vignette.
为了明确起见,这里仅使用一个循环和 Rcpp 糖的列式索引是相同的:
Just to be explicit, here is the same using just one loop and the column-wise indexing of 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>
这篇关于Rcpp 矩阵:遍历行,一次一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!