How can I have an option for SAVE to skip saving a variable if it doesn't exist in the workspace?

16 views (last 30 days)
I am saving a sizeable number of variables from my workspace into a MAT-file. However, some of these variables may not exist at times. In that case, SAVE command returns an error. I want to know if I can pass an option into SAVE such that it simply skips a variable from its list if the variable doesn't exist in the workspace.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
The ability to skip variables that do not exist while using the SAVE command is not available in MATLAB.
As a workaround, you can compile a cell-array with the names of the variables to be saved. The script can then loop through the array and save (with the -append option) the variable only if it exists.
x = 3.4; y = 'abcxyz'; z = struct('key1','value1','key2','value2');
variableList = {'x','y','z','w'};
for variableIndex = 1:length(variableList)
if exist(variableList{variableIndex})
if exist('myDataFile.mat')
save('myDataFile.mat',variableList{variableIndex},'-append')
else
save('myDataFile.mat',variableList{variableIndex})
end
end
end

More Answers (0)

Categories

Find more on Get Started with Optimization Toolbox in Help Center and File Exchange

Products


Release

R2008a

Community Treasure Hunt

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

Start Hunting!