That example was half the answer, but it required enumerating the components to be saved, which doesn't grow well. I wanted to automatically traverse the app data structure and FIND programmatically all components whose values should be saved. Here's what worked for me. This solution will restore all components that match, leave alone all components that are not found in the saved data, and warn (in the Matlab window) of any saved state that did not match a component in the program.
This creates a robust save/load mechanism that will not crash even in the presence of version changes that add or delete components.
function SaveSettings(app)
state = struct();
props = properties(app);
for i = 1:length(props)
name = props{i};
comp = app.(name); % May be a component or a property, so far...
c = string(class(comp));
if c == "matlab.ui.control.NumericEditField" ...
|| c == "matlab.ui.control.EditField" ...
|| c == "matlab.ui.control.CheckBox"
state.(name)= comp.Value;
elseif c == "matlab.ui.control.DropDown"
% These are weird, had to be specially handled to save a string
% instead of an index into the list:
v = comp.Value;
state.(name)= comp.Items{v};
end
end
save('SavedSettings.mat','state');
end
function LoadSettings(app)
load('SavedSettings.mat', 'state')
fields = fieldnames(state);
for i = 1:length(fields)
name = fields{i};
try % or could use isprop(app, name) to test presence
comp = app.(name);
comp.Value = state.(name);
catch err
disp(['Did not use saved field', name, ': ', err.identifier])
end
end
end