How to declare multiple global variables?

68 views (last 30 days)
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!

Accepted Answer

Image Analyst
Image Analyst on 3 Jul 2016
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

More Answers (1)

Geoff Hayes
Geoff Hayes on 2 Jul 2016
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 Comment
Geoff Hayes
Geoff Hayes on 3 Jul 2016
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?

Sign in to comment.

Categories

Find more on Scope Variables and Generate Names in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!