[R] Matrix variable in C code

Gabor Csardi csardi at rmki.kfki.hu
Thu Feb 2 15:32:46 CET 2006


On Thu, Feb 02, 2006 at 03:11:42PM +0100, depire at inrets.fr wrote:
[...]
> 
> and my test code in C is:
> ================================================
> SEXP VPCEfron(SEXP f, SEXP SR, SEXP ZR, SEXP DIR, SEXP nsR, SEXP rho)
> {
> 	int taille=INTEGER(nsR)[0];
[...]
> 
> All works, except ZS, the variable ZS is a matrix in R, and when i try to give
> to C code, with ZR, ZR is only a vector.
> 
> How to obtain a matrix variable in C ?

A matrix is the same as a vector (stored columnwise), except that is has a 
dim attribute. Use can use SET_DIM to set the dim attribute, and GET_dim to
query it. Eg:

int nrow=INTEGER(GET_DIM(ZR))[0];
int ncol=INTEGER(GET_DIM(ZR))[1];

To access the values in the matrix you might use something like:

#define RMATRIX(m,i,j) (REAL(m)[ INTEGER(GET_DIM(m))[0]*(j)+(i) ])

and then 

RMATRIX(ZR, 0, 1), etc. works. Note that according to this #define the matrix
is indexed from zero.

Gabor


-- 
Csardi Gabor <csardi at rmki.kfki.hu>    MTA RMKI, ELTE TTK




More information about the R-help mailing list