MEX file crashing for an array of cell

2 次查看(过去 30 天)
Hello!
I have written a MEX file that takes in a cell array of double matrices, each of dimension 250x1000. The cell array dimensions are 29x1. The MEX file is assigning the value 3 to all the entries of the matrices. However, whenever I call the MEX file, MATLAB crashes. I have no idea why this is happening as the index of my matrices are in the allowed range.
To reproduce the bug/error, please run the following code on the attached files:
load test;
test(pp);
The files are large in size and are available here.
For a quick review, the test.c file is as follows:
#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;
double *inMatrix;
int mom, cellSize, jcell;
mwIndex i, j, count;
mwSize ncol, nrow;
// Read the cell
cell = prhs[0];
dims = mxGetDimensions(prhs[0]);
for (jcell=1; jcell<dims[0]; jcell++) {
cellArray = mxGetCell(cell,jcell);
inMatrix = mxGetPr(cellArray);
nrow = mxGetM(cellArray);
ncol = mxGetN(cellArray);
printf("%d, %d, %d\n", nrow, ncol, cellSize);
count = 0;
for(i=0;i<nrow;i++){
for(j=0;j<ncol;j++){
inMatrix[count] = 3;
count++;
}
}
}
}
Thanks

采纳的回答

Jan
Jan 2015-7-2
If you want to assign all elements of the cell array, start at jcell=0 (as in the example http://www.mathworks.com/matlabcentral/answers/84135-getting-the-contents-from-cells-in-a-cell-array-using-mex).
mxGetCell replies a NULL pointer if the input is not a cell or if the cell element is not initialized. Check this in every case:
cellArray = mxGetCell(cell,jcell);
if (cellArray == NULL) {
... perform an error or an exception
}
You are writing directly into the input array. This is dangerous, because you do not check if this is a shared array. Never modify the inputs in a C-Mex function, if you are not really sure about what you are doing. But here this can lead to bad values in Matlab, but not to a crash.
jcell is an int and dims an mwSize. Are you sure that jcell<dims[0] does, what you expect? The same happens for i, j and nrow, ncol. Better rely on the same integer types.
  1 个评论
Ubaid Ullah
Ubaid Ullah 2015-7-3
Thanks .. actually some of the matrices in the array were of type SPARSE and some were of type FULL. The SPARSE matrices were creating problem as I was treating them full matrices, assuming they have nrowxncol size.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by