How to extract string data from an input cell matrix in a MEX file?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
MathWorks Support Team
am 2 Dez. 2009
Bearbeitet: MathWorks Support Team
am 17 Okt. 2023
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.
Akzeptierte Antwort
MathWorks Support Team
am 17 Okt. 2023
Bearbeitet: MathWorks Support Team
am 17 Okt. 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 Kommentar
James Tursa
am 19 Okt. 2018
Bearbeitet: James Tursa
am 19 Okt. 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Write C Functions Callable from MATLAB (MEX Files) finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!