How to declare multiple global variables?

64 次查看(过去 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!

采纳的回答

Image Analyst
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

更多回答(1 个)

Geoff Hayes
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
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 CenterFile 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!

Translated by