flatten a struct in matlab

One way to flatten a struct in Matlab is to use the struct2cell function to create a cell array of the struct's fields, then use cat to concatenate those cell arrays into a single cell array. Here's an example:

main.m
myStruct.field1 = 1;
myStruct.field2.nestedField = 'hello';
myStruct.field3 = [1 2 3];

flat = cat(1, struct2cell(myStruct));
126 chars
6 lines

This will create a single column cell array flat containing the contents of all fields in the struct, in the order they appear in myStruct. Note that if your struct contains nested structs, this method will not automatically flatten them - you'll need to process them in a separate step if needed.

related categories

gistlibby LogSnag