Trimming the Size of a Array of Structures in a MEX file
1 view (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
James Tursa
on 4 Feb 2013
Edited: James Tursa
on 4 Feb 2013
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 Comments
James Tursa
on 4 Feb 2013
Edited: James Tursa
on 4 Feb 2013
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
on 4 Feb 2013
Edited: James Tursa
on 4 Feb 2013
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.
More Answers (0)
See Also
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!