Kahibaro
Discord Login Register

Local vs Global Variables

Scope of Variables in MATLAB Functions

When you start writing your own functions in MATLAB, one of the first practical issues you meet is variable scope. Scope describes where a variable exists and where it can be seen or used. In MATLAB functions, variables are usually local, but you can also create global variables that are shared across multiple workspaces. Understanding the difference is essential to avoid confusing bugs and to keep your code clear.

In this chapter you will focus on what makes a variable local inside a function, how that differs from a global variable, how to declare globals correctly, and what typical pitfalls you should avoid when using global state.

Local Variables Inside Functions

Every time you call a function, MATLAB creates a new workspace for that function. This workspace contains only the variables that belong to that function call. These variables are called local variables.

A local variable can appear in several ways. It can be an input argument to the function, for example x and y in a header such as function z = add(x, y). It can also be created inside the function body through assignment, such as temp = x + y. In both cases, the variable exists only while the function runs, and it is visible only inside that function.

If you try to use a local variable from outside the function, MATLAB will not find it. For example, a variable named temp that you compute inside a function is not accessible in the Command Window once the function finishes. Similarly, a variable with the same name may exist in the base workspace, but a function does not automatically see it. The function uses its own local version of the variable.

Each call of a function also gets its own copy of local variables. If a function calls itself recursively, or if you call the same function twice in a row, one call cannot directly change the local variables of another call. This isolation is one of the main benefits of local scope. It keeps the internal workings of a function separate from the rest of your code.

Global Variables and the `global` Keyword

Sometimes you might want different workspaces to share the same variable. MATLAB provides global variables for this purpose. A global variable is not confined to a single function workspace. Instead, it can be accessed from any function or from the base workspace, as long as each of those places declares the variable as global with the global keyword.

To create or use a global variable, you write a line like

matlab
global counter

inside the function or in the Command Window. This tells MATLAB that counter in that workspace refers to a special shared storage, not to a regular local variable.

The name of a global variable is tied to its spelling. If you write global counter and somewhere else write global Counter, those are two separate global variables because MATLAB is case sensitive for variable names. Every workspace that needs to access the same global must use the exact same name with global.

A global variable is created the first time any workspace assigns a value to it after declaring it global. For example, if you type in the Command Window

matlab
global rate
rate = 0.05;

then any function that also contains global rate can read and modify this same rate variable.

Sharing Data Across Functions with Globals

Global variables act as a shared pool of state. Any function that declares the variable as global can read or change its value. This can be used to share configuration values or counters between functions without passing them as input or output arguments.

For example, you might have a global variable that stores a constant parameter you want to use in many functions, such as a sample rate or a default threshold. You can set the value once in the base workspace, and then each function that declares the same name as global can see that value.

In practice, you use globals by repeating the same declaration in each place where you need access. A typical pattern inside a function looks like

matlab
function y = applyGain(x)
    global gain
    y = gain * x;
end

This function does not define gain locally. Instead, it expects some other part of your program, such as a script or another function, to have already declared global gain and assigned a numeric value to it. If that has not happened, gain will be empty and the computation will not behave as intended.

The sharing of data through globals is immediate. If one function changes the value of a global, that new value is visible in all other workspaces that share the same global. There is no need to return a result and pass it to other functions. This convenience is also a source of risk.

Lifetime and Visibility Differences

Local and global variables differ both in where they are visible and for how long they exist.

A local variable inside a function exists only while that function runs. When the function finishes, its workspace is cleared and all local variables disappear, unless they are returned as outputs. If you call the function again, MATLAB creates a new set of local variables. You can think of each function call as a fresh environment.

In contrast, a global variable exists across function calls. Its lifetime continues until you clear it or end the MATLAB session. You can remove a global variable using clear global name or by using clear all which also clears globals. As long as it is not cleared, the value is preserved between calls to any function that uses it.

Visibility for local variables is restricted to the function they belong to. Another function cannot directly access them, even if it has a variable with the same name. These are separate variables that just happen to share an identifier. Global variables, on the other hand, are visible wherever they are declared as global. Once declared, they do not need to be passed through argument lists.

The base workspace, which you see in the Command Window, is also separate from function workspaces. If you declare a variable there without global, it is local to the base workspace and functions do not see it. Only when you declare the same name as global in both the base workspace and inside functions do you get shared visibility.

Name Conflicts and Shadowing

Because global variables share names with local variables, you need to understand what happens if both exist. In a function, if you write global a then the name a in that function refers to the global variable. If you later assign a = 10 inside that function, you are modifying the global, not creating a local variable.

If you do not use the global keyword in a function, any assignment to a variable name creates or modifies a local variable instead. This holds even if a global variable with the same name exists in some other workspace. In this case, the local variable shadows the global variable inside that function. The function will not see the global value. It will only use its own local one.

It is possible for a name to refer to a global in one function and to a local variable in another. This can be very confusing when you try to understand where a value is coming from. You might expect functions to use the same shared value but instead they use different local copies. This is one reason why many MATLAB programmers avoid global variables whenever possible.

Name conflicts can also occur with functions and variables, but that is a separate topic. In the context of local and global variables, the main point is that the global declaration decides whether a variable name refers to shared storage or to a regular local location in that workspace.

Why Globals Are Risky for Beginners

Even though globals are simple to use, they can lead to code that is difficult to debug and maintain. Because any function that knows the name can change the value, it becomes hard to track which part of your code modified the variable and when. Bugs related to unexpected changes in globals can be subtle and time consuming to find.

Another problem is that functions that depend on globals are less self contained. Their behavior is tied to external state that is not visible in their input and output arguments. To understand or test such a function, you must also know the current values of all global variables it uses. This reduces clarity and makes reuse more difficult.

Globals can also encourage poor design. Instead of defining clear data flow through function arguments, you might be tempted to store everything in a handful of global variables. Over time, this makes your programs more fragile. A small change in one place can have surprising effects elsewhere, because many parts of the code are coupled through the same global names.

For these reasons, globals are best treated as a last resort. In most beginner programs, it is almost always possible to redesign the code so that needed values are passed as inputs and returned as outputs, or stored in more structured ways such as fields of a structure.

Safer Alternatives to Global Variables

Rather than relying on globals, you can usually use function arguments, return values, and more explicit data structures to share information. Passing variables directly between functions makes the dependencies obvious. When you read a function header, you can see exactly what information it requires and what it produces.

In some cases, you might want to keep state inside a function between calls without exposing it globally. MATLAB provides persistent variables for that purpose, which you can explore later. Persistent variables live across function calls but remain local to that function and are not visible anywhere else. This offers a controlled way to store state without polluting many workspaces.

Another alternative is to group related data into a structure and pass that structure around. For example, you might create a structure named settings with fields like settings.gain and settings.rate. Each function that needs these values can accept settings as an input. This keeps configuration data together and avoids scattering many independent global variables.

For larger programs, you can also organize your code into classes and objects, but that belongs to more advanced topics. At the beginner level, careful use of function arguments, outputs, and simple containers such as structures is usually enough to avoid needing global variables.

Important points to remember:

  1. Variables inside a function are local. They exist only while the function runs and are not visible outside it.
  2. A variable becomes global only if you declare it with global name in each workspace that should share it.
  3. Global variables are shared across functions and the base workspace, and any of these can change their values.
  4. If you assign to a name without global inside a function, you are creating or changing a local variable, even if a global with the same name exists.
  5. Overuse of global variables makes code harder to understand, test, and debug. Prefer passing data through function inputs and outputs.

Views: 3

Comments

Please login to add a comment.

Don't have an account? Register now!