我有一個來自不同作者的年老代碼,他們使用多年的全局變量和以下挑戰:我從一個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