MATLAB: How to extract string data from an input cell matrix in a MEX file

MATLAB

I have created the following cell in MATLAB:
x = {'alpha' 'bravo' 'charlie';'Xray' 'yankee' 'Zulu'}
I would like to see a sample code for a MEX file to extract the contents of the cell in C or C++ environment.

Best Answer

The following C program shows one way to extract the cell contents:
#include "mex.h"
#include "string.h"
void printArray(char charArray[])
{
int itr;
int len = strlen(charArray);
mexPrintf("The length of C array is %d \n", len);
mexPrintf("The value of C array is %s", charArray);
mexPrintf("\n--------------\n");
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
const mxArray *cell_element_ptr;
char* c_array;
mwIndex i;
mwSize total_num_of_cells, buflen;
int status;
/*Extract the cotents of MATLAB cell into the C array*/
total_num_of_cells = mxGetNumberOfElements(prhs[0]);
for(i=0;i<total_num_of_cells;i++){
cell_element_ptr = mxGetCell(prhs[0],i);
buflen = mxGetN(cell_element_ptr)*sizeof(mxChar)+1;
c_array = mxMalloc(buflen);
status = mxGetString(cell_element_ptr,c_array,buflen);
mexPrintf("The length of cell element %d is: %d \n", i, strlen(c_array));
printArray(c_array);
mxFree(c_array);
}
mexPrintf("Success\n");
}
To use the above MEX file, execute the following commands in MATLAB:
mex -v extractCellMatrix.c % Compiles the MEX file
x = {'alpha' 'bravo' 'charlie';'Xray' 'yankee' 'Zulu'} % Creates the cell matrix
extractCellMatrix(x) % Pass the cell array to the MEX function