How to save all global variables?
13 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Guido
el 14 de Feb. de 2013
Comentada: Stephen23
el 20 de Dic. de 2017
The save command only saves those Matlab variables which are visible in a workspace. It does not, however, cover the global variables which are reported by who('global') but have not been declared as globals in this workspace. Is there a way to save all global variables in a given Matlab session, even if their names are not known a priori?
Respuesta aceptada
Jan
el 14 de Feb. de 2013
Editada: Jan
el 21 de Feb. de 2013
While I recommend not to use global variables, because they impede the debugging dramatically, there should be a solution to your problem.
When you want to save the variables, which are found by who('global'), it would be a simple idea to use globalVars = who('global') to get a list of these variables at first. Then the values might not be known inside a function. So, sigh, I have to suggest to one and only case, which I cannot solve without eval.
globalVars = who('global');
for iVar = 1:numel(globalVars)
eval(sprintf('global %s', globalVars{iVar})); % [EDITED]
end
This can overwrite local variables by accident, e.g. if "globalVars" is a global variable itself, this approach is buggy. Therefore I strongly recommend to choose a different strategy. The complexity caused by the automatic access of global variables cannot be managed reliably. And when there is the decision between a complicated and inherently buggy method and a clean and clear one, <not every sentence has to be finished>
4 comentarios
Sean Herbert
el 25 de Feb. de 2016
another way, without a for loop:
globalVars = who('global')'; %notice the '
glob_str = sprintf('global %s',strjoin(globalVars));
%create them
eval(glob_str)
Más respuestas (1)
Tarun Luthra
el 19 de Dic. de 2017
I am trying to do same thing. how do I save something inside a function such as a global variable out to workspace?
0 comentarios
Ver también
Categorías
Más información sobre Variables en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!