[Rcpp-devel] '[' operator of NumericMatrix

Dirk Eddelbuettel edd at debian.org
Thu Aug 23 02:34:15 CEST 2012


On 22 August 2012 at 17:42, Dirk Eddelbuettel wrote:
| 
| On 22 August 2012 at 17:11, Peng Yu wrote:
| | Hi,
| | 
| | I'm trying to use '[' operator to extract elements from NumericMatrix.
| | But it seems that it is not what I expected. Is it a bug or a feature?
| 
| Neither but mostly your misunderstanding of C syntax carrying forward in C++
| as never ever worked in a matrix class.

Sorry: "as this never ever worked in any C++ matrix class" is what I meant to write.

| In C (and C++), the expression   i,j  leaved just j.
| 
| You want    x(i, j)   here.

Here is somewhat edited version of your test script:

R> suppressMessages(library(inline))
R> src='
+   Rcpp::NumericMatrix x(mx);
+   for(int i = 0; i < x.nrow(); ++ i) {
+      for(int j = 0; j < x.ncol(); ++ j) {
+        Rcpp::Rcout << "(" << i << "," << j << ")=" << x(i, j) << " ";
+      }
+      Rcpp::Rcout << std::endl;
+   }
+   return R_NilValue;
+ '
R> fun <- cxxfunction(signature(mx="numeric"), src, plugin="Rcpp")
R> orig <- matrix(1:12, 3, 4)
R> orig
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
R> fun(orig)
(0,0)=1 (0,1)=4 (0,2)=7 (0,3)=10 
(1,0)=2 (1,1)=5 (1,2)=8 (1,3)=11 
(2,0)=3 (2,1)=6 (2,2)=9 (2,3)=12 
NULL
R> 

-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com  


More information about the Rcpp-devel mailing list