How to declare multiple global variables?
67 ビュー (過去 30 日間)
古いコメントを表示
Hello Friends,
I have multiple variables in my script file, say, var1, var2, var3. I want to declare them global variable. I tried to do the following:
function setGlobalDomain(val1, val2, val3)
global Domain1, Domain2, Domain3;
[Domain1, Domain2, Domain3] = deal(val1, val2, val3);
end
Next, I think I have to do the following to access them:
function r = getGlobalDomain
global Domain1, Domain2, Domain;
r = Domain1, Domain2, Domain3;
end
However, I am unable to understand how to do it. I think what I am doing above is valid to declare only one global variable, not to multiple global variables.
I will appreciate any advise!
0 件のコメント
採用された回答
Image Analyst
2016 年 7 月 3 日
Try something like this:
function r = getGlobalDomain(val1, val2, val3)
% Declare global variables.
global Domain1, Domain2, Domain;
% Now, after the above line executes, getGlobalDomain() can see them and work with them.
% Create output based on inputs and global variables:
% Domain1, Domain2, and Domain must already exist or this won't work.
% If they don't exist yet, you can define them first though
% just assign something to them.
% Now assign output variable. Use whatever formula you want, for example...
r = val1 * Domain1 + val2 ^ Domain2 - log(Domain3);
end % Optional line
0 件のコメント
その他の回答 (1 件)
Geoff Hayes
2016 年 7 月 2 日
hello_world - remove the commas that separate your global variables. So instead of
global Domain1, Domain2, Domain3;
do
global Domain1 Domain2 Domain3;
Also, in getGlobalDomain if you are trying to concatenate the three global variables as r then you must wrap in square brackets or braces (if cell array) as
r = [Domain1 Domain2 Domain3]; % with or without commas
Finally, ask yourself if the global variables are absolutely necessary. Can you do something else instead? Why not return the values from your setGlobalDomain function instead of declaring them as global? How are the get and set methods being used?
1 件のコメント
Geoff Hayes
2016 年 7 月 3 日
Please clarify what you mean by how to pass multiple variables there in your setGlobalDomain. You are passing three parameters into this function. Do you mean how to initialize the global variables?
参考
カテゴリ
Help Center および File Exchange で Scope Variables and Generate Names についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!