Skip to content
Prev 207332 / 398506 Next

matrix to a C function

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: