I'm hoping someone can help me with a problem I'm having with some mex code I've written. After calling the same mex function many times, the matlab will have no response. I post the code here:
void mexFunction(int nlhs, mxArray *plhs[], /* Output variables */
int nrhs, const mxArray *prhs[]) /* Input variables */
{
const char *fieldnames[3]; //This will hold field names.
fieldnames[0] = (char*)mxMalloc(20);
fieldnames[0] = "mean";
plhs[0] = mxCreateCellMatrix(11, 1);
mxArray *cells = plhs[0];
mxArray *treeNodeMean;
double *mean;
for(int i = 0; i < 10; ++i) {
mxArray* treeNode = mxCreateStructMatrix(1,1,1,fieldnames);
mxSetCell(cells, i , treeNode);//set treeNode to tree
//initialize
treeNodeMean = mxCreateDoubleMatrix(2,58, mxREAL);
//set values
mean = mxGetPr(treeNodeMean);
for(int j = 0; j<=(58*2);j++) {
mean[j] = (double)j;
}
//set treeNode
mxSetFieldByNumber(treeNode,0,0, treeNodeMean);//(pointer,index,fieldNumber,value)
}
return;
}
for i = 1:100
A = createTrees;
end
Matlab not responding after long runing.
for(int j = 0; j<=(58*2);j++) {
mean[j] = (double)j;
}
from the mex function, the case of “Matlab not responding after long runing.” will disappear. So, How can I solve the "No response" problem. Thanks a lot.
The for loop in question is accessing the array out of bounds. C-style indexing goes from 0
to N-1
instead of 1
to N
(as in MATLAB), so your loop termination condition should be j<(58*2)
instead of <=
.
You may also want to double-check the loop termination condition for your outer loop (over i
), because that is only looping over 10 elements despite you allocating memory for 11.