How to shrink a pre-allocated array in a C-Mex?
Show older comments
What is a fast and secure way to shrink a pre-allocated array inside a C-Mex function?
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
// PREREQUISITES: -----------------------------
double *p, *q;
int n = 1000, m;
// Pre-allocate an array for the maximum size of [1 x 1000]:
plhs[0] = mxCreateDoubleMatrix(1, n, mxReal);
p = mxGetPr(plhs[0]);
// Some dummy calculations: ...
p[0] = 1.0;
p[1] = 2.0;
m = 2; // Only 2 elements used here for example
// THE ACTUAL QUESTION: --------------------------
// Part 1: Set N only:
mxSetN(plhs[0], m);
// Part 2: re-allocate:
q = mxRealloc(p, m * sizeof(double));
// Part 3: Check success of realloc:
// A failing mxRealloc stops with an error in normal MEX functions,
// but not "in a MAT or engine standalone application" (see: doc mxRealloc)
if (q == NULL) {
mexErrMsgIdAndTxt("JSimon:TestFunc_MEX:ReAllocFail",
"Re-allocation of output failed.");
}
// Part 4: Update data pointer on demand:
if (q != p) { // Usually the smaller array is at the same location
mxSetPr(plhs[0], q);
// Part 5: Should I free the old memory?
// In a normal MEX function the memory manager cares, but in
// MAT or engine applications?
// mxFree(p);
// NO, DON'T DO THIS. See: doc mxRealloc:
// If the memory location changes, mxRealloc frees the original
// memory block pointed to by ptr.
}
}
Is Part 1 enough already, or are the other parts required for a stable code? Is this documented by MathWorks?
Accepted Answer
More Answers (0)
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!