Listing 2. A MEX Function #include #include #include #include "mex.h" /* This is the interface function to MATLAB, with the generic name of "mexFunction". Generally these interface functions just check arguments and format the input, then pass control off to an inner "meat" function. */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ int M, R, T, NsoFar; const int *dim_array; /* it is possible to handle variable numbers of arguments with MEX, but my function is very specific */ if((nrhs != 6) || (nlhs != 2)) mexErrMsgTxt("wrong # of args to c_mLAT"); /* Find array dimensions, in this case corresponding to number of electrodes, number of time points, and number of trials, depending on the input */ dim_array = mxGetDimensions(prhs[0]); M = dim_array[0]; R = dim_array[1]; T = dim_array[2]; NsoFar = mxGetM(prhs[1]); /* Allocate memory for return variables. This memory is allocated in the Matlab environment and does not have to be freed explicitly */ plhs[0] = mxCreateDoubleMatrix(NsoFar, R, mxREAL); plhs[1] = mxCreateDoubleMatrix(NsoFar, T , mxREAL); /* Call the inner function */ latcalc(mxGetPr(prhs[0]), mxGetPr(prhs[1]), mxGetPr(prhs[2]), mxGetPr(prhs[3]), mxGetPr(prhs[4]), mxGetPr(prhs[5]), mxGetPr(plhs[0]), mxGetPr(plhs[1]), M, R, T, NsoFar); } /* Some of the inner function is presented here */ void latcalc(double *x, double *erp, double *alpha, double *tau, double *coupling, double *range, double *inresultlat, double *inresulterp, int M, int R, int T, int NsoFar){ double *s; double *latency; double *ZZ; double *Z; double *colbase; double *colbase2; double sumlat; double meanlat; int index; int nnza; int q,w; double maximum; int pad = 200; int alpha_is_nonzero = 1; int j,p,m,t,n,i; /* allocates memory in matlab environment */ s = mxCalloc(1, (pad * 2 + T) * NsoFar * sizeof(double)); /* prints error message into matlab window */ if(!s) mexErrMsgTxt("Failure to alloc. s in mLAT.\n"); /* ... Code Cut Here ... */ /* An example of one of the more nested loops inside the code... illustrating one way to go about accessing matlab arrays without getting too confused. This is a little hairy, but doing it directly is far more confusing. And using the MATLAB functions from within C are slow. If you want to know what exactly this is doing, read the paper by Knuth et al.*/ for(j=NsoFar-1;j>=0;j--){ for(p=0;p