[Rcpp-devel] matrix indexing

Romain Francois francoisromain at free.fr
Tue Jan 26 11:13:59 CET 2010


Hi,

We now (in svn) have matrix-like indexing through operator() for all 
vectors : (character, integer, numeric, raw, logical, generic and 
expression).

Here is an example from the unit tests of NumericVector :

 > funx <- cfunction(signature(x = "numeric" ), '
+ NumericVector m(x) ;
+ double trace = 0.0 ;
+ for( size_t i=0 ; i<4; i++){
+ trace += m(i,i) ;
+ }
+ return wrap( trace ) ;
+ ', Rcpp = TRUE, includes = "using namespace Rcpp;"  )
 > x <- matrix( 1:16 + .5, ncol = 4 )
 > diag( x )
[1]  1.5  6.5 11.5 16.5
 > sum( diag( x ) )
[1] 36
 > funx(x)
[1] 36

Arbitrary dimension array indexing is planned, but not yet implemented. 
I'll probably hard-code dimension 3 and let variadic templates take care 
of generalization to 4+ dimensions since it is not used that much.

Or maybe we can do it through classic C variable argument lists so that 
it does not depend on C++0x ? anyone familiar with this ?

Romain

On 01/23/2010 09:05 PM, Romain Francois wrote:
> Hello,
>
> Motivated by Christophe's question on R-help (cc'ed), I'd like to add
> facilities for matrix (and maybe arrays) indexing into the new Rcpp api.
>
> The classic api already ships matrix indexing through RcppMatrix and
> RcppMatrixView classes. I'm not a big fan of using round brackets for
> indexing, but apparently one cannot pass more than one parameter to []
> so ... I guess I'll have to sacrifice look and feel for a minute.
>
>
> Anyway I was thinking we can maybe add NumericVector::operator()( int,
> int) (other vectors as well), so that we can do :
>
> NumericVector m(x) ;
> double x11 = m(0,0) ;
>
>
> I was also thinking maybe making some sort of indexer class to take care
> of conversion of 2 indices into 1d index; something like this pseudo code :
>
> NumericVector m(x) ;
> NumericVector::MatrixIndexer indexer(m) ;
> double x11 = m[ indexer(0,0) ] ;
>
> But this might be even more ugly than operator().
>
>
> Given than a REALSXP can change its mind about being a matrix, I'm not
> sure I want to subclass NumericVector into NumericMatrix, etc. ...
>
> Ideas ?
>
> Romain
>


-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- http://tr.im/KfKn : Rcpp 0.7.2
|- http://tr.im/JOlc : External pointers with Rcpp
`- http://tr.im/JFqa : R Journal, Volume 1/2, December 2009



More information about the Rcpp-devel mailing list