开发者

global in Matlab [closed]

开发者 https://www.devze.com 2023-01-05 04:47 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying th开发者_运维百科is question so that it can be reopened, visit the help center. Closed 9 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消