MATLAB: How to have an option for SAVE to skip saving a variable if it doesn’t exist in the workspace

existMATLABsaveskipvariable

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.

Best Answer

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