[Rcpp-devel] Accessing matrix elements

Michael Braun braunm at MIT.EDU
Sun May 15 00:00:04 CEST 2011

Hi, Rcpp-friends:

File this post under "rookie mistake, "educational illustration," or "feature request," but I noticed something in accessing elements from Rcpp matrices that I found somewhat curious.  Consider the following code, for which the objective is just to print elements of a matrix.

body <- '

using namespace std;
using namespace Rcpp;

NumericMatrix x(x_);

int i, j;
int m = x.nrow();
int n = x.ncol();

for (i=0; i<m; i++) {
  for (j=0; j<n; j++) {
    cout << x[i,j] << "  ";  // Accessing element using square brackets
  cout << endl;
cout << endl << endl;

for (i=0; i<m; i++) {
  for (j=0; j<n; j++) {
    cout << x(i,j) << "  ";  // Accessing element using parentheses
  cout << endl;

return (wrap(0));

func <- cxxfunction(signature(x_="numeric"),

x <- matrix(as.numeric(c(1,2,3,4)), nrow=2, ncol=2)
print(x)   // Displaying the matrix, as intended

In R, I would access the matrix elements using the x[i,j] syntax, but clearly that does not work in Rcpp.  The x(i,j) syntax is correct, and I suppose that this is what is documented.  But when using the square brackets, there is no error either at compile-time or run-time.  And since the behavior seems "undefined" (at least to me), it is very easy to make the mistake of using R-style square brackets instead of Rcpp-style parentheses.  Now, I am not claiming that this is a bug.  But I wonder how hard it might be to overload the square brackets so they behave the same way an R user might expect.  And if there is a good reason why Rcpp behaves this way, I'm interested in learning what it is, for future reference.



Michael Braun
Associate Professor of Management Science (Marketing Group)
MIT Sloan School of Management
100 Main St.., E62-535
Cambridge, MA 02139
braunm at mit.edu

More information about the Rcpp-devel mailing list