Getting the contents from cells in a cell array using MEX

I have a 5x1 cell array (each cell has a single number) and I want to pass this cell array as a parameter to a mex function (written in C) and view the contents of the cells. I have written the following mex function.
#include <math.h>
#include <matrix.h>
#include <mex.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
const mwSize *dims;
const mxArray *cell;
const mxArray *cellArray;
mwIndex jcell;
double *output;
cell = prhs[0];
output = mxGetPr(cell);
dims = mxGetDimensions(prhs[0]);
for (jcell=0; jcell<dims[0]; jcell++) {
cellArray = mxGetCell(cell,jcell);
printf("The content at %d is %d\n",jcell,cellArray);
}
return;
}
Lets call the C code above test.c test.c compiles without problems. When I call test(mycell), where mycell is:
mycell = cell(5,1);
mycell{1,1} = 1;
mycell{2,1} = 2;
mycell{3,1} = 3;
mycell{4,1} = 4;
mycell{5,1} = 5;
the mex function prints the following:
The content at 0 is 152353696
The content at 1 is 152353248
The content at 2 is 152354704
The content at 3 is 152353920
The content at 4 is 152352800
What I want is 1, 2, 3, 4, 5 instead of those rubbish numbers. Can anyone please help me solving the problem here, because I can´t see it. I have searched this forum and various sources without success.

 采纳的回答

mxGetCell replies the pointer to the mxArray element. You currently display the address in the memory, while you want to show the contents:
double *p;
mxArray *cellElement; // Typo: * was missing, thanks James
...
for (jcell=0; jcell<dims[0]; jcell++) {
cellElement = mxGetCell(cell,jcell);
p = mxGetPr(cellElement)
mexPrintf("The content at %d is %g\n", jcell, *p);
Notice that this will fail, if the contents is not a double array or if it is empty. a = cell(1,1) create an unpopulated cell, such that mxGetCell replies a NULL pointer and a direct access can crash Matlab.

3 个评论

Thanks, this works. although I had to write (int)*p in the mexPrintf function to get 1,2,3,4,5 and not 0,0,0,0,0.
Then you did not use my suggested %g but %d.
Typo:
mxArray *cellEllement; // missing the * above

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File 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