[Rcpp-devel] Pointer to Rcpp::NumericMatrix

Simon Fuller simonfuller9 at gmail.com
Tue May 29 13:18:05 CEST 2012


Hello,

I would like to use a pointer to an Rcpp::NumericMatrix to operate
upon elements, linearly, row by row.

For Rcpp::NumericVector this seems easy, since I can use a
straightforward iterator, i.e.

Rcpp::NumericVector::iterator it = myVector->begin();

But for NumericMatrix this seems more difficult for my purposes.

>From the source (Matrix.h) it seems you use a flat matrix with an
offset, and as far as I can tell you go column by column:

inline int offset( int i, int j) const {
    return i + nrows * j ;
}

It seems from here that an iterator does indeed move column by column
but I could be wrong:

  void import_matrix_expression( const MatrixBase<RTYPE,NA,MAT>&
other, int nr, int nc ){
        iterator start = VECTOR::begin() ;
        for( int j=0; j<nc; j++){
            for( int i=0; i<nr; i++, ++start){
                *start = other(i,j) ;
            }
        }
    }

Using pointers seems the best way to go, for me, as it simplifies the
code structure without requiring copying of large amounts of data. I
can probably use an offset with an iterator, but I thought I would ask
whether there is another, better, way, while retaining pointers to
NumericMatrix, e.g., to random access elements of a NumericMatrix via
a pointer to it.

Thank you very much for your help,

Simon


More information about the Rcpp-devel mailing list