[R] matrix to a C function
Romain Francois
romain.francois at dbmail.com
Sat Jan 23 20:49:17 CET 2010
Christophe,
That's another question for the R-devel mailing list.
A few things however.
Short answer : no it is not possible. I don't think x[i,j] is even
syntactically valid in C or C++.
I'd suggest you to give a go at the .Call interface that lets you
manipulate R objects directly. So in your example with the .Call
interface you'd only have to pass one argument and figure out the matrix
dimensions internally with the C api of R. Something like this perhaps:
SEXP pr( SEXP x ){
/* extract the "dim" attribute */
SEXP dim = getAttrib( x, R_DimSymbol ) ;
int nrow = INTEGER(dim)[0];
int ncol = INTEGER(dim)[1];
/* extracting the pointer just once */
double * p = REAL(x) ;
int i,j;
for( i=0; i<nrow; i++){
for( j=0; j<ncol; j++){
Rprintf( " %f ", p[i+nrow*j] ) ;
}
Rprintf( "\\n" ) ;
};
return R_NilValue ; /* NULL */
}
You can use the regular print function (called PrintValue internally),
which will nicely take care of aligning the columns properly, etc ...
SEXP pr( SEXP x ){
PrintValue( x ) ;
return( R_NilValue ) ;
}
Finally, you can use C++ through the Rcpp package and write something
like this :
SEXP pr( SEXP x){
RcppMatrixView<double> m(x) ;
int i,j;
int nrow = m.rows() ;
int ncol = m.cols() ;
for( i=0; i<nrow; i++){
for( j=0; j<ncol; j++){
Rprintf( " %f", m(i,j) ) ;
}
Rprintf( "\\n" ) ;
}
return R_NilValue ;
}
The indexing here is done with the round brackets here because it is
just not valid to have more than one parameters passed to operator[] in
C or C++.
Romain
On 01/23/2010 05:04 PM, Christophe Genolini wrote:
>
> Hi the list,
> Is there a way to give a matrix to a C function, and then to use it as a
> matrix ?
> I write a function to print a matrix, but I use it as a vector :
>
> 1. void printMatrix(double *mTraj,int *nbCol, int *nbLigne){
> 2. int i=0,j=0;
> 3. for(i=0 ; i < *nbLigne ; i++){
> 4. for(j=0 ; j < *nbCol ; j++){
> 5. Rprintf(" %f",mTraj[i * *nbCol + j]);
> 6. }
> 7. Rprintf("\n");
> 8. }
> 9. }
>
> I would like to use it as a matrix (line 5 changes) :
>
> 1. void printMatrix(double *mTraj,int *nbCol, int *nbLigne){
> 2. int i=0,j=0;
> 3. for(i=0 ; i < *nbLigne ; i++){
> 4. for(j=0 ; j < *nbCol ; j++){
> 5. Rprintf(" %f",mTraj[i,j]);
> 6. }
> 7. Rprintf("\n");
> 8. }
> 9. }
>
> It does not work, but is there an solution close to this ?
>
> Thanks.
> Christophe
--
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 R-help
mailing list