Trimming the Size of a Array of Structures in a MEX file

조회 수: 1 (최근 30일)
Jonathan Sullivan
Jonathan Sullivan 2013년 2월 4일
Hi all.
So i'm having a bit of an issue array of structures in a MEX file. I first initialize the array of structures to size that is (most likely) much larger than I need. Then I loop over an operation an unknown number of times, each time filling the next structure in that array of structures. Then, once done, I'd like to trim that array of structures to be the size that it needs to be, and no more.
I initialize the array of structure as follows:
structOut = mxCreateStructMatrix(MAX_FILES, 1, NUMBER_OF_FIELDS, fieldnames);
I have been trimming the size of structOut using the following command:
mxSetM(structOut,cnt);
This does successfully change the size of the variable outputted, but it does not free up the memory associated the orphaned headers (i.e. outStruct(cnt+1:end)).
Effecftively, I'd like to implement something functionally equivalent to the code below, but in mex form:
structOut(cnt+1:end) = [];
What can you recommend to accomplish this, without concurring a large computation time penalty, nor leaking memory.

채택된 답변

James Tursa
James Tursa 2013년 2월 4일
편집: James Tursa 2013년 2월 4일
It is possible to do the equivalent of structOut(cnt+1:end) = [] in a mex routine (see below), but first I would ask if it is really necessary. You will only be saving (end-cnt)*NUMBER_OF_FIELDS*4 bytes of memory (or *8 for 64-bit systems). That is, the only thing in memory you will be saving are a bunch of NULL pointers, not mxArray headers. Your mxSetM method is fast, does not leak memory, and gets the job done.
If you do decide to do it anyway, here is the code:
mxArray **ma, **ms; // EDIT
mwSize i;
:
ms = mxGetData(structOut);
ma = mxMalloc(cnt*NUMBER_OF_FIELDS*sizeof(*ma));
for( i=0; i<cnt*NUMBER_OF_FIELDS; i++ ) {
ma[i] = ms[i];
}
mxFree(ms);
mxSetData(structOut,ma);
mxSetM(structOut,cnt);
  댓글 수: 3
James Tursa
James Tursa 2013년 2월 4일
편집: James Tursa 2013년 2월 4일
Yes, good catch on the ma and ms declarations. I wrote the code off the top of my head (not at a machine with MATLAB installed) so it was untested (I should have pointed that out & warned you). I edited the code above based on your correction.
James Tursa
James Tursa 2013년 2월 4일
편집: James Tursa 2013년 2월 4일
I should also add a comment related to the use of mxMalloc and manually copying the data instead of just using mxRealloc. I avoid mxRealloc in these cases on purpose because it does not always free the "excess" memory involved when shrinking a memory block.

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

추가 답변 (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