Skip to content

[Rcpp-devel] Accessing matrix elements

2 messages · Michael Braun, Dirk Eddelbuettel

#
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.

library(inline)
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"),
                    body,
                    plugin="Rcpp"
                    )

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


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.

Thanks,

Michael









-------------------------------------------
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
617-253-3436
#
Hi Michael,
On 14 May 2011 at 18:00, Michael Braun wrote:
| 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.

Rookie mistake -- as 

|     cout << x[i,j] << "  ";  // Accessing element using square brackets

simply will not pass any C++ compiler despite whatever magic pixie Rcpp
sprinkles on top. There is no opeator[] that can take two arguments. So use
the round brackets, and rest assured that all other C++ Matrix classes I know
of do the same (e.g. Armadillo is always a good one to check.

Dirk