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?

 채택된 답변

Jan
Jan 2013년 2월 14일
편집: Jan 2013년 2월 21일

1 개 추천

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

Thanks a lot. That helped quite a bit. There is just a small typo in the answer. The sigh line should read
eval(sprintf('global %s', globalVars{iVar}));
Jan
Jan 2013년 2월 21일
Typo is fixed. But I have a bad conscience that I suggest a method containing the two evil commands EVAL and GLOBAL simultaneously. Hopefully nobody has seen this and reminds me, when I claim vainly, that there are always better ways then EVAL.
another way, without a for loop:
globalVars = who('global')'; %notice the '
glob_str = sprintf('global %s',strjoin(globalVars));
%create them
eval(glob_str)
Stephen23
Stephen23 2016년 2월 25일
편집: Stephen23 2016년 2월 25일
These "solutions" should all be given the caveat "Only for entertainment purposes, NEVER use in serious code!"

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Tarun Luthra
Tarun Luthra 2017년 12월 19일

0 개 추천

I am trying to do same thing. how do I save something inside a function such as a global variable out to workspace?

카테고리

도움말 센터File Exchange에서 Workspace Variables and MAT Files에 대해 자세히 알아보기

질문:

2013년 2월 14일

댓글:

2017년 12월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by