MATLAB: How to dynamically grow a structure in a MEX-file using the available MX routines

apidynamicallygrowgrowingMATLABmexmxresizestructure

How do I dynamically grow a structure in a MEX-file using the available MX routines?

Best Answer

There is no direct API available to accomplish this. We recommended that you use the mxGetData, mxSetData, and the mxRealloc routines to dynamically grow your data. For example, the following MEX-function code will allow dynamic resizing of a structure using the available API. You should be able to copy this code to a file called 'growing.c' and compile this using the MEX command and run it in MATLAB:
/* growing.c */
/* Sample MEX function to dynamically grow a structure to create a vector structure */
#include "mex.h"
void mexFunction(int nlhs, mxArray * plhs[], int nrhs, const mxArray * prhs[])
{
int m = 1;
int n = 0;
const char * fieldnames[] = {"field1", "field2"};
int n_fields = sizeof(fieldnames)/sizeof(*fieldnames);
int i,j,new_n;
mxArray * pa;
/* Start with a vector structure */
pa = mxCreateStructMatrix(m, n, n_fields, fieldnames);
/* Grow the vector */
new_n = n + 20;
mxSetData(pa, mxRealloc(mxGetData(pa), new_n * n_fields *
sizeof(mxArray *)));
mxSetN(pa, new_n);
/* NOTE: mxRealloc does not initialize additional memory */
for(i=n; i < new_n; i++) {
for(j=0; j < n_fields; j++) {
mxSetFieldByNumber(pa, i, j, NULL);
}
}
plhs[0] = pa;
}
In MATLAB I see:
>> mex growing.c
>> growing
ans =
1x20 struct array with fields:
field1
field2
NOTE: Please be aware that if you are not careful in using the mxSet* and mxGet* routines, your application may contain memory leaks or other issues.