How to efficiently save variables from an app

11 views (last 30 days)
Ryan Wall
Ryan Wall on 12 Apr 2018
Edited: Stephen23 on 13 Apr 2018
Hey All,
I'm building a simple app in AppDesigner. I want a simple "save" function, and I'm utilizing the uisave function. This is the code I have, and it works:
Data=app.Data;
K=app.KVals;
ID=app.BatchID;
SaveDat={'Data',...
'K',...
'ID'};
DummyFilename=[datestr(now,'yyyy_mmdd') '_' app.BatchID '.mat'];
uisave(SaveDat,DummyFilename);
The issue is I'm calling the app variables into a separate variable just to save them. I'd prefer to just use the string:
SaveDat = {'app.Data','app.KVals','app.BatchID'};
but when I do I get the error "Variables app.Data app.KVals app.Batch ID not found"
It seems like a little thing, but what could be done to fix this?

Answers (1)

Stephen23
Stephen23 on 13 Apr 2018
Edited: Stephen23 on 13 Apr 2018
There is no easy way to do this using uisave, because it requires the variable names and not the names of fields of a structure. One simple solution would be to simply save the complete structure: this would give a (perhaps superfluous) structure in the .mat file, however this might be acceptable to you. Another option would be to magically generate those variables, but this is not recommended and in fact the MATLAB documentation specifically advises against doing this. Read this to know why:
One relatively easy workaround is to use uiputfile and save together, because save has an option '-struct' which saves the fields of a scalar structure as individual variables:
app.data = 1:4;
app.text = 'blah';
name = 'somefile.mat';
[fnm,pth] = uiputfile(name);
if ischar(fnm)
save(fullfile(pth,fnm),'-struct','app')
end
This creates a .mat file with two variables corresponding to the two fields in the input structure. You can also specify the required fields: see the save documentation for more information.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!