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

1 次查看(过去 30 天)
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.

采纳的回答

MathWorks Support Team
编辑:MathWorks Support Team 2023-10-17
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 个评论
James Tursa
James Tursa 2018-10-19
编辑:James Tursa 2018-10-19
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Write C Functions Callable from MATLAB (MEX Files) 的更多信息

标签

尚未输入任何标签。

产品

Community Treasure Hunt

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

Start Hunting!

Translated by