How to declare multiple global variables?

조회 수: 79 (최근 30일)
hello_world
hello_world 2016년 7월 2일
답변: Image Analyst 2016년 7월 3일
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에서 Variables에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by