Trimming the Size of a Array of Structures in a MEX file
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
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
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
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 Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!