MEX: Problem creating a cell matrix and assign it to the output

조회 수: 4 (최근 30일)
AP
AP 2012년 10월 24일
Dear All,
By using a MEX file, I am trying to loop through array "group_ptr" with size 1000×1 to make a cell with size 4×1. group_ptr(i) contains the group ID which "i" belongs to. The 4 groups have different number of elements. My MEX file does other things beside to creating this cell. It takes one input and generates 4 outputs. When it gets to making the cell, MATLAB crashes.
However, when I comment the part for making the cell and reduce the number of outputs to 3, MEX file works fine. I would be grateful if someone could help me what the problem could be.
Below is the part of my code which creates this cell. The MEX file has 4 output which the last one is this cell.
#define CELLGROUP plhs[3]
mxArray *CellArray_ptr;
CellArray_ptr = mxCreateCellMatrix( 4, 1 );
double *a = new double[ 1000 ];
for( mwIndex i=0; i<4; i++ )
{
int counter = 0;
for( int j=0; j < 1000; j++ )
{
if( (mwIndex)group_ptr[ j ]== (i+1) )
a[ counter++ ] = j;
}
mxArray *A;
A = mxCreateDoubleMatrix( counter, 1, mxREAL );
memcpy( mxGetPr(A), a, sizeof(double)*counter );
mxSetCell( CellArray_ptr, i, A );
mxDestroyArray( A );
}
CELLGROUP = CellArray_ptr;
delete[] a;
Thanks,
Ahmad

채택된 답변

James Tursa
James Tursa 2012년 10월 24일
편집: James Tursa 2012년 10월 24일
Your code:
mxSetCell( CellArray_ptr, i, A );
mxDestroyArray( A ); // get rid of this line
Get rid of the mxDestroyArray call. When you call the mxSetCell function, three things happen:
1) The address of A gets put into the i'th cell location in the CellArray_ptr variable
2) The type of A gets changed from "temporary" to "sub-element"
3) The address of A gets removed from the garbage collection list.
After the mxSetCell function call, A is literally now part of the CellArray_ptr array. Its ultimate clearing will depend entirely on what happens to CellArray_ptr. When you call mxDestroyArray on A, you are invalidating part of a legitimate variable. Hence when MATLAB tries to access or clear CellArray_ptr later on it crashes since it accesses invalid memory.
  댓글 수: 5
AP
AP 2012년 10월 24일
James,
How can I privately send you my email address so you could let me know when it is published?
James Tursa
James Tursa 2012년 10월 24일
편집: James Tursa 2012년 10월 24일
You can use the Contact Author link:
I can probably send you a preliminary incomplete doc if you are interested, with all the usual caveats about potential errors in the doc and using undocumented functions. Just e-mail me through the link and let me know.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile 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