MATLAB: How to build nested mxStructs in C for use with MATLAB MEX-files or the MATLAB Compiler

levelMATLABmultistructures

I would like to build a multilevel nested structure in C, either as an output from a MEX-file or as an input to a MATLAB Compiler-generated shared library.

Best Answer

Nested structures can be most easily built in C using the mxCreateStructMatrix() / mxCreateStructArray() and mxSetField() / mxSetFieldByNumber() functions.
The example file SUBSTRUCTEX.C below demonstrates the procedure in a MEX-file; the process will be similar for MATLAB Compiler-generated shared libraries. substructex.c is a modified version of the mxcreatestructarray.c example mentioned on the mxCreateStructArray documentation in the External Interfaces manual; you should first be comfortable with the workflow demonstrated in that simpler case, which you can view by executing the following MATLAB command:
doc mxCreateStructArray
Download the C-code attached below and compile it using the MEX command:
mex -v substructex.c
You can demonstrate this nested structure example by executing it, and examining the results:
a = substructex
a =
1x4 struct array with fields:
name
phone
hometown
a(2)
ans =
name: 'Mary Smith'
phone: 3912
hometown: [1x1 struct]
a(2).hometown
ans =
city: 'London'
country: 'UK'