MATLAB: How to build a mex return structure

mexmxarray

I am unable to figure out how to build and attach matrices to the structure I have being returned
mwSize dims[2] = {1,NumChans};
plhs[0] = mxCreateStructArray(2, dims, NUMBER_OF_FIELDS, field_names);
I want to place matrices in one of the fields where I'll have a different one for each structure element. I can't seem to find any examples how best to do this, would there possibly be such an example?
Thanks

Best Answer

You can create an mxArray as you would anywhere else, e.g.
mxArray* myArray = mxCreateDoubleMatrix( 3, 4, mxREAL );
double* dataPtr = mxGetPr( myArray );
// Some code here to fill up myArray however you want using dataPtr
mxSetField( plhs[0], 0, field_names{1}, myArray ); // Assign matrix to first field name of 1st structure in array
mxSetField( plhs[1], 1, field_names{1}, myOtherArray ); // Assign matrix to first field name of 2nd structure in array
etc
with myOtherArray created by whatever method you choose also.