tags:

views:

38

answers:

2
+3  Q: 

global in Matlab

hi guys im noob at Matlab and i cannot understand global variables. like=> global x y z what does global means? could you give me example? any help will be appreciated.

+4  A: 

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.

Edric
could we say that global variables among functions likes the attributes in a class?
ibrahimyilmaz
Not at all. global defines a variable shared by every part of matlab. Actually the exact opposite of class attributes.
Marc
+3  A: 

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.

Marc

related questions