Search code examples
matlabstructurematlab-struct

Save fields of branched structure with dynamic names in matlab


I need to know how to save just one branch of a structure in MATLAB. The structure contains more levels with more fields per level. For example:

data.level1.level21  
data.level1.level22

I want now to save the branches data.level1.level21 and data.level1.level21 individually. I have tried the following but it doesn't work:

firstLevelName = fieldnames(data);
secondLevelNames = fieldnames(data.(firstLevelName{1}));

for pL = 1:length(secondLevelNames)
        save([filename '.mat'], '-struct', 'data', firstLevelName{1}, secondLevelNames{pL});
end

Solution

  • The structure-saving method that you're trying to use doesn't work quite the way you are expecting. All the arguments after your struct variable name are fields of that struct to save.

    The way MATLAB is interpreting your code is that you're trying to save the level1, and level21 fields of data which obviously doesn't work since level21 is a subfield of level1 not data.

    To save the nested fields, the easiest thing is probably to create a new variable pointing to the structure data.level and then call save on that and specify the specific fields to save.

    level1 = data.level1;
    
    for pL = 1:numel(secondLevelNames)
        save(filename, '-struct', 'level1', secondLevelNames{pL});
    end
    

    If you actually want the double nesting in the saved data, you would need to create a new structure containing only the data that you wanted and then save that.

    for pL = 1:numel(secondLevelNames)
        newstruct = struct(firstLevelName{1}, struct());
        newstruct.(secondLevelNames{pL}) = data.(firstLevelName{1}).(secondLevelNames{pL});
    
        save(filename, '-struct', 'newstruct')
    end