我有一个来自不同作者的年老代码,他们使用多年的全局变量和以下挑战:我从一个excel文件导入了多个(> 200)变量。它们不在函数内部,它们不被指定为全局函数。对于函数的工作,它们必须是因为有一个函数调用函数2.函数1只调用一次,而函数2调用大于10000次,所以我希望全局函数在函数1中。我怎么能轻松地将它们全部变成全局变量并将它们传递给函数2?将所有当前工作空间变量转换为全局变量
例子(方案)
% function1
% global *other variables exist here already*
% this function calls function2 at a certain point further below
L=whos
save L % some variables a b c ... are parameters in function2
% function2
% global *other variables exist here already*
load L % i dont want to load my workspace everytime, I rather wish to just access global variables a b c...
% the problem is that my variables sometimes change name and I want to have
% them all global in an automatic way. Or live with a workaround.
感谢您的耐心,我很愿意回答大家的提问!
更新我:
我设法与这是因为它涉及到代码手动操纵林不完全满意解决方法。所以这是最好的临时解决方案。
%可以说你有一些工作区变量,并将它们保存在这个名字下,然后加载它们: load workspacevars.mat;
L =谁%给你这些变量的名称作为字符串列 L = L”%和形式,让你可以使用它作为全球(如行)
%不幸的是使用全球大号不工作为了我。有任何想法吗? %我不得不在工作区中转到L,然后单击并将生成的长字符串拖到文本编辑器中。 %那里,我删除了大括号{}和'',因为这是全球喜欢有他们的变量:纯。
%最后它看起来是这样的:全球VAR1 VAR2 VAR3 ....
相关:http ://stackoverflow.com/q/26361946/2777181 – 2014-11-21 21:16:42
你能解释一下评论“问题在于我的变量有时会改变名称”吗? – TroyHaskin 2014-11-21 22:37:21
如果使用[嵌套函数](http://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html?refresh=true),那么变量将在'function1'和'function2'之间共享因为'function2'不会将它们声明为输入。 – TroyHaskin 2014-11-21 22:42:11