Search code examples
cmatlabsparse-matrixmex

Accessing sparse matrix created in MEX from MATLAB


I have created a sparse matrix in a MEX-file following the example shown in here. Now how do I access this matrix from MATLAB as a whole.

#define NZMAX 4
#define ROWS  4
#define COLS  2

int            rows=ROWS, cols=COLS;
mxArray       *ptr_array; /* Pointer to created sparse array. */
static double  static_pr_data[NZMAX] = {5.8, 6.2, 5.9, 6.1};
static int     static_ir_data[NZMAX] = {0, 2, 1, 3};
static int     static_jc_data[COLS+1] = {0, 2, 4};
double        *start_of_pr;
int           *start_of_ir, *start_of_jc;
mxArray       *array_ptr;

/* Create a sparse array. */    
array_ptr = mxCreateSparse(rows, cols, NZMAX, mxREAL); 

/* Place pr data into the newly created sparse array. */ 
start_of_pr = (double *)mxGetPr(array_ptr); 
memcpy(start_of_pr, static_pr_data, NZMAX*sizeof(double));

/* Place ir data into the newly created sparse array. */ 
start_of_ir = (int *)mxGetIr(array_ptr); 
memcpy(start_of_ir, static_ir_data, NZMAX*sizeof(int));

/* Place jc data into the newly created sparse array. */ 
start_of_jc = (int *)mxGetJc(array_ptr); 
memcpy(start_of_jc, static_jc_data, NZMAX*sizeof(int));

/* ... Use the sparse array in some fashion. */
/* When finished with the mxArray, deallocate it. */
mxDestroyArray(array_ptr);

Also while storing the values in static_pr_data, ic_data and jc_data is it necessary to store the values in column major format? Is it possible to store in row major format (since it will speed up my calculation)?


Solution

  • In the example you link to, the last statement is

    mxDestroyArray(array_ptr);
    

    Instead of destroying the array, you need to return it as the output of your MEX-function. Your MEX-function C/C++ source code should have a function named mexFunction (the entry point for the MEX-function) that looks like this:

    void mexFunction(int nlhs, mxArray * plhs[], int nrhs, const mxArray * prhs[])
    

    To return an output from the MEX-function, assign it into the plhs array, like this:

    plhs[0] = array_ptr; // instead of mxDestroyArray(array_ptr);
    

    Compile the code into a MEX-function (Let's call it sparsetest). Invoke it from MATLAB like this:

    >> output = sparsetest;
    

    Now output is a MATLAB variable containing the sparse matrix you created in your MEX-function.

    As for storing the data in row-major format, that is not possible. MATLAB only handles column-major sparse matrices.