MATLAB: Get a subset of a structure array in mex

mex

Is it possible to get a subset of a structure array in mex? In other words, the mex equivalent of the following in Matlab:
s2 = s1(2:5); %s1 is a structure array
In my (current) use case, the structure array is empty, although fields have been defined.

Best Answer

This is the code I ended up using. At the end of the day I essentially wanted to have an object "template" (i.e. field names defined) that I then populate with values at the appropriate time.
Prior to the example code below, I've initialized empty "template" objects into a cell array, 1 for each unique type of object that I've encountered.
//- This is specific to my code, but ref_object is an empty structure
// BUT with fields, like in Matlab => s = struct('a',{},'b',{},'c',{})
int object_id = data.object_ids[object_data_index];
mxArray *ref_object = mxGetCell(data.objects,object_id);
//- Create a fresh structure/structure array from the reference
//- Copies the field names
mxArray *return_obj = mxDuplicateArray(ref_object);
//- I know the # of fields, this is a bit of a note to my self
// in that I'm not sure which of these will execute faster
//- "data" is a C structure
//Not sure which is better ...
//int n_fields = data.child_count_object[object_data_index];
int n_fields = mxGetNumberOfFields(return_obj);
//- This is the magic that I think I pulled from one of James Tursa's other
// posts (and this one too). The important part is that the "data" (in mxGetData, mxSetData)
// for a structure or structure array is a linear array of pointers to mxArrays.
mxArray **object_data = mxCalloc(n_fields*n_objects,sizeof(mxArray*));
mxSetData(return_obj,object_data);
mxSetN(return_obj,n_objects);
return return_obj;