How to declare multiple global variables?

66 visualizzazioni (ultimi 30 giorni)
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!

Risposta accettata

Image Analyst
Image Analyst il 3 Lug 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

Più risposte (1)

Geoff Hayes
Geoff Hayes il 2 Lug 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 Commento
Geoff Hayes
Geoff Hayes il 3 Lug 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?

Accedi per commentare.

Categorie

Scopri di più su Scope Variables and Generate Names in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by