2011-05-08 181 views
20

這是我第一次嘗試Rcpp,這個非常簡單的問題給我帶來了麻煩。我想使用嵌套for循環來操作矩陣的單個值,每次一列。我的目標該腳本會是這個樣子:Rcpp矩陣:循環遍歷行,一次一列

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]; 

道歉,如果這是一個愚蠢的新手問題。任何提示將不勝感激!

+2

我以前說過的話,我會說它又一次:'rcpp-devel'是解決這些問題的好地方。 – 2011-05-08 23:36:27

+0

@DirkEddelbuettel雖然我明白'rcpp-devel'列表可能會更多地接觸到使用'rcpp'的人,在我看來,stackoverflow更容易訪問。 – jbaums 2012-08-17 00:03:18

+0

@jbaums:當然,但所有關鍵的rcpp-devel貢獻者只有一個在這裏看到問題。減少問題的眼球... – 2012-08-17 00:46:35

回答

30

不能在單個[ ]表達式中使用多個索引。這是一個C語言的限制,我知道克服的C++矩陣類系統或庫。因此改用()

修復這一點,你實際上並沒有通過srccxxfunction()的錯誤,我們得到這樣的:

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糖列Wise索引相同:

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> 
+3

美麗!感謝Dirk的迴應。我將把未來的問題(如果有的話)引導到Rcpp-devel列表。再次感謝! – Vincent 2011-05-08 23:48:46

+4

而不是'Am(j,_)'你可以使用'Am.row(j)'。 – 2016-05-13 19:02:29