[R] Using .Call function to do matrix calculation

John Fox jfox at mcmaster.ca
Mon Mar 17 21:59:05 CET 2003

Dear Deli Wang,

Perhaps this isn't what you're looking for, but it occurs to me that you 
probably can do this problem without compiled code as sapply(1:nrow(a), 
function(i) sum(a[i,] * b[,i])). This doesn't use much memory, and though 
it may execute slowly, you may also get the answer before you debug your C 

I hope that this helps,

At 01:42 PM 3/17/2003 -0600, Deli Wang wrote:
>Because of high dimensionality of matrix, I can not use R matrix calculation
>operator to do matrix multiplication.  My interest is the diagonal elements
>of J*J matrix( which can be got by multiplying matrix a(J*K) and b(K*J)),
>where J is too big to allocate enough memory for it.  In order to get those
>diagonals, I tried .Call function to do that. Here is c program for .Call.
>#include <R.h>
>#include <Rinternals.h>
>SEXP var(SEXP a,SEXP b){
>  int i,J=nrows(a),j,K=nrows(b),k;
>  SEXP varbeta;
>  PROTECT(varbeta=allocVector(REALSXP,J));
>  for(j=0;j<J;j++){
>   for(k=0;k<J;k++){
>   if(j==k){
>         for(i=0;i<K;i++) REAL(varbeta)[j]+=REAL(a)[j+i*J]*REAL(b)[i+k*K];}
>     }
>    }
>  return (varbeta);
>  }
>This function did not work at all. The warning messages is the segmentation
>Could some expert help me out?
>R-help at stat.math.ethz.ch mailing list

John Fox
Department of Sociology
McMaster University
email: jfox at mcmaster.ca
web: http://www.socsci.mcmaster.ca/jfox

More information about the R-help mailing list