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

7 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 27 de Jun. de 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

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Productos


Versión

R2008a

Community Treasure Hunt

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

Start Hunting!

Translated by