I am new to Matlab and have difficulty understanding global variables. For example
global x y z
What does global
mean? Could you give me an example?
Without global
, a declared variable has a limited scope, that is, it cannot be used outside the "part" of matlab where it is declared. This wiki article has a decent discussion of what scope is in a generic sense.
For Example, if you declare a variable inside a function definition, then that variable can only be used inside that function - not in another function. If you define a function at the command line (the so-called "base workspace") it cannot be used in functions.
global
defines a variable in the "global" scope - it can be used anywhere, in any function, etc. Except in limited cases, it is generally a bad idea, since it makes controlling how and when a variable has changed very difficult. You are usually better off returning something from a function, then passing it to another.
The keyword GLOBAL
in MATLAB lets you define variables in one place and have them visible in another. The statement global x y z
declares x
y
and z
to be global. If that definition were placed inside a function scope, and a corresponding global
definition in a separate function, then the two functions can share data without the need to pass parameters. Like so:
%% fcn1.m
function fcn1( val )
global store
store = val
%% fcn2.m
function y = fcn2()
global store
y = store;
Thus you can call fcn1
to store a value, and use fcn2
to retrieve the value later.
Using GLOBAL
data in this way hides the dependencies between your functions, and is considered pretty bad practice.
精彩评论