Re: [Rd] passing matrix as argument to a C function

From: Prof Brian Ripley <>
Date: Sun 03 Dec 2006 - 08:25:09 GMT

The data in an R matrix is not stored as double **A, but as double *A: it is just a vector in R, with attributes.

There are lots of examples of manipulating R matrixes via .C: one is src/library/stats/src/kmeans.c.

The code for crossprod is not at all hard to find: it is in src/main/array.c. However, is just a call to an LAPACK function. The code there for matprod would be more informative.

On Sun, 3 Dec 2006, Christos Hatzis wrote:

> 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
> <>
> ______________________________________________
> mailing list

Brian D. Ripley,        
Professor of Applied Statistics,
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

______________________________________________ mailing list
Received on Sun Dec 03 19:28:29 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Sun 03 Dec 2006 - 21:30:57 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.