Documentation

global

Declare variables as global

Syntax

global var1 ... varN

Description

example

global var1 ... varNdeclares variablesvar1 ... varNas global in scope.

Ordinarily, each MATLAB®function has its own local variables, which are separate from those of other functions and from those of the base workspace. However, if several functions all declare a particular variable name asglobal, then they all share a single copy of that variable. Any change of value to that variable, in any function, is visible to all the functions that declare it as global.

If the global variable does not exist the first time you issue theglobalstatement, it is initialized to an empty0x0matrix.

If a variable with the same name as the global variable already exists in the current workspace, MATLAB issues a warning and changes the value of that variable and its scope to match the global variable.

Examples

collapse all

Create a function in your current working folder that sets the value of a global variable.

functionsetGlobalx(val)globalx x = val;

Create a function in your current working folder that returns the value of a global variable. These two functions have separate function workspaces, but they both can access the global variable.

functionr = getGlobalxglobalx r = x;

Set the value of the global variable,x, and obtain it from a different workspace.

setGlobalx(1138) r = getGlobalx
r = 1138

Assign a value to the global variable using the function that you defined in the previous example.

clearallsetGlobalx(42)

Display the value of the global variable,x. Even though the variable is global, it is not accessible at the command line.

x
Undefined function or variable 'x'.

Declarexas a global variable at the command line, and display its value.

globalx x
x = 42

Change the value ofxand use the function that you defined in the previous example to return the global value from a different workspace.

x = 1701; r = getGlobalx
r = 1701

Tips

  • To clear a global variable from all workspaces, useclear globalvariable.

  • To clear a global variable from the current workspace but not other workspaces, useclearvariable.

Introduced before R2006a

Was this topic helpful?