FlattenStruct.m 994 B

123456789101112131415161718192021222324252627282930
  1. function [ structOut, cellArray, fieldNames ] = FlattenStruct( structIn, fieldPrefix )
  2. % FLATTENSTRUCT flattens a hierarchical structure array into a flat version.
  3. % field names are concated with _
  4. cellArray = struct2cell( structIn );
  5. fieldNames = fieldnames( structIn );
  6. fieldInd = 1;
  7. while fieldInd <= numel( fieldNames )
  8. if exist( 'fieldPrefix', 'var' ) && ~isempty( fieldPrefix )
  9. fieldNames{fieldInd} = [fieldPrefix '_' fieldNames{fieldInd}];
  10. end
  11. if isstruct( cellArray{fieldInd, 1, 1} )
  12. subStruct = [cellArray{fieldInd, :, :}];
  13. [~, subCellArray, subFieldNames] = FlattenStruct( subStruct, fieldNames{fieldInd} );
  14. cellArray = [cellArray; subCellArray];
  15. fieldNames = [fieldNames; subFieldNames];
  16. cellArray(fieldInd, :, :) = '';
  17. fieldNames(fieldInd) = '';
  18. else
  19. fieldInd = fieldInd + 1;
  20. end
  21. end
  22. structOut = cell2struct( cellArray, fieldNames );
  23. structOut = orderfields( structOut );
  24. end