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

1 visualizzazione (ultimi 30 giorni)
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.

Risposta accettata

MathWorks Support Team
MathWorks Support Team il 17 Ott 2023
Modificato: MathWorks Support Team il 17 Ott 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 Commento
James Tursa
James Tursa il 19 Ott 2018
Modificato: James Tursa il 19 Ott 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.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Write C Functions Callable from MATLAB (MEX Files) in Help Center e File Exchange

Tag

Non è stata ancora inserito alcun tag.

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by