[Rcpp-devel] Pointer to Rcpp::NumericMatrix

Dirk Eddelbuettel edd at debian.org
Tue May 29 13:43:19 CEST 2012


Hi Simon,

On 29 May 2012 at 12:18, Simon Fuller wrote:
| 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 ;
| }

This should do exactly what R does where a "matrix" really is allocated the
same way a vector is, but with a 'rows times cols' capacity.
 
| 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.

I am not quite clear about what you want to achieve and why "pointers" would
be best. C++ style favors iterators, code clarity may favour simple indexing.
Neither approach implies copying.

You could look at examples/ConvolveBenchmarks where (for the vector case) a
number of different access mechanisms are compared and times, including
iterators as well as fallbacks to pointers.  

If it helps, RcppArmadillo and RcppEigen have proper (as in: linear algebra)
matrix types too.

Dirk
 
| Thank you very much for your help,
| 
| Simon
| _______________________________________________
| Rcpp-devel mailing list
| Rcpp-devel at lists.r-forge.r-project.org
| https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

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


More information about the Rcpp-devel mailing list