MATLAB Function Reference
  Go to function:
    Search    Help Desk 
global    Examples   See Also

Define global variables

Syntax

Description

global X Y Z defines X, Y, and Z as global in scope.

Ordinarily, each MATLAB function, defined by an M-file, has its own local variables, which are separate from those of other functions, and from those of the base workspace and nonfunction scripts. However, if several functions, and possibly the base workspace, all declare a particular name as global, they all share a single copy of that variable. Any assignment to that variable, in any function, is available to all the functions declaring it global. If the global variable does not exist the first time you issue the global statement, it is initializied to the empty matrix. By convention, global variable names are often long with all capital letters (not required).

It is an error to declare a variable global if:

Remarks

Use clear global variable to clear a global variable from the global workspace. Use clear variable to clear the global link from the current workspace without affecting the value of the global.

To use a global within a callback, declare the global, use it, then clear the global link from the workspace. This avoids declaring the global after it has been referenced. For example:

uicontrol('style','pushbutton','CallBack',...

'global MY_GLOBAL,disp(MY_GLOBAL),MY_GLOBAL = MY_GLOBAL+1,clear MY_GLOBAL',...

'string','count')

Examples

Here is the code for the functions tic and toc (some comments abridged), which manipulate a stopwatch-like timer. The global variable TICTOC is shared by the two functions, but it is invisible in the base workspace or in any other functions that do not declare it.

See Also

clear, isglobal, who



[ Previous | Help Desk | Next ]