[Rd] passing matrix as argument to a C function

Christos Hatzis christos at nuverabio.com
Sun Dec 3 07:17:29 CET 2006


Hi,
 
Although this is not directly an R-related question, it is relevant as I am
trying to port some R code to C to speed things up in a computation.

I am working through my first attempts to generate and link compiled C code
in R.  I could make the 'convolve' function to work and similar functions
that take vectors as arguments.  In my application I need to pass a couple
of matrices to the C function and could not figure out how to make it work
in C.
 
As an example, I tried to code first a simple matrix-vector product
function.  Here is my code:

void matrix_mult( double **A, double *b, double *ab, int *nrow, int *ncol )
{
    int i, j, nr = *nrow, nc = *ncol;
    for( i = 0; i < nr; i++ )
    {
        ab[i] = 0.0;
        for( j = 0; j < nc; j++ )
            ab[i] += A[i][j] * b[j];
    }
} 
 
As I understand, passing the matrix A as (double **) is not standard C and
does not compile (to try things out I am using Microsoft Visual C++ compiler
in Windows XP).  I tried to find the C code for crossprod for some hints,
but could not locate it in the R source.  But probably this does not use the
.C interface.

Is there a way this can be done with .C?  I suspect it will use in some way
the "vector of pointers to row vectors" concept, but I am not familiar
enough in C yet to figure it out.  Any hints on how in can be done with
.Call if easier?

Thank you.
-Christos  

Christos Hatzis, Ph.D.
Nuvera Biosciences, Inc.
400 West Cummings Park
Suite 5350
Woburn, MA 01801
Tel: 781-938-3830
www.nuverabio.com <http://www.nuverabio.com/>



More information about the R-devel mailing list