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

1 view (last 30 days)
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.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 17 Oct 2023
Edited: MathWorks Support Team on 17 Oct 2023
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
  1 Comment
James Tursa
James Tursa on 19 Oct 2018
Edited: James Tursa on 19 Oct 2018
Please post your code. Either you are doing something wrong or you are doing something that you are not telling us. mxGetCell( ) simply copies a single pointer that takes an insignificant amount of time. There is no way that 20 such calls can take 12 seconds. Something else must be going on. And it would be better that you open up a new Question for this rather than hijack this thread.

Sign in to comment.

More Answers (0)

Categories

Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange

Tags

No tags entered yet.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!