MATLAB: How to convert all data from structures & substructures in a cell into a table

cellMATLABstructuretable

I have a cell vector, in which each entry is a structure. Some of the fields in a structure is also a structure. For example:
Data{1,1}.a=1;
Data{1,1}.b='b';
Data{1,1}.K.x='x';
Data{1,1}.K.y='y';
Data{1,1}.K.z='z';is
Data{2,1}.a=10;
Data{2,1}.K.x='x';
Data{2,1}.K.v='v';
I want to convert the fields and data from structure into a table. For example, I would like to see:
T =
a b x y z v
———————————
1 'b' 'x' 'y' 'z' ''
10 '' '' 'x' '' '' 'v'

Best Answer

Please download the attached file 'heteroStruct2table.m' and see the following example:
Data{1,1}.a=1;
Data{1,1}.b='b';
Data{1,1}.K.x='x';
Data{1,1}.K.y='y';
Data{1,1}.K.z='z';
Data{2,1}.a=10;
Data{2,1}.K.x='x';
Data{2,1}.K.v='v';
T = heteroStruct2table(Data,'K')
What the "heteroStruct2table.m" file does is to
1. add the missing fields in the original structs to make it become homogeneous
2. convert a cell array of homogeneous structs to table