TExcelTAD
Home › MATLAB / Octave › Variable Scope

Variable Scope

The scope of a variable is the part of a program where it is visible. MATLAB's rules are simple: every function call has its own workspace, scripts share the workspace of whoever runs them, and only a few special mechanisms (arguments, return values, nested functions, global and persistent) let data cross those boundaries.

Workspaces

Code Uses which workspace?
Command Window The base workspace
A script run from the Command Window The base workspace
A script called from a function That function's workspace
A function Its own, fresh for every call
An anonymous function Its arguments plus the values captured when it was created
matlab · try it yourself
x = 10;
show_x();
y = double_it(x);
fprintf('x is still %d, y is %d\n', x, y);

function show_x()
fprintf('inside show_x, exist(''x'') = %d\n', exist('x', 'var'));
end

function out = double_it(x)
x = x * 2;               % changes the local copy only
out = x;
end
inside show_x, exist('x') = 0
x is still 10, y is 20

show_x can't see x, and double_it changes only its own copy. MATLAB passes arguments by value (it avoids actually copying large arrays until you modify them, so this is efficient). To change a variable, return the new value and assign it in the caller: x = double_it(x).

Loop variables and if blocks don't create scopes

Unlike many languages, blocks like if, for and while do not have their own scope. A variable created inside a loop still exists afterwards, and the loop variable keeps its last value:

matlab · try it yourself
for k = 1:3
    lastSquare = k^2;
end
fprintf('k = %d, lastSquare = %d\n', k, lastSquare);
if true
    inside = 'created in an if block';
end
disp(inside)
k = 3, lastSquare = 9
created in an if block

persistent variables

A persistent variable belongs to one function but keeps its value between calls. It starts as an empty matrix the first time, which you test with isempty. Typical uses: counters, caches, one-time initialisation:

matlab · try it yourself
for k = 1:3
    fprintf('call number %d\n', counter());
end
fprintf('fib(30) = %d\n', fib_cached(30));
fprintf('fib(50) = %d\n', fib_cached(50));

function n = counter()
persistent count
if isempty(count)
    count = 0;
end
count = count + 1;
n = count;
end

function f = fib_cached(n)
persistent memo
if isempty(memo)
    memo = [1 1];
end
if n <= numel(memo)
    f = memo(n);
    return
end
for k = numel(memo)+1:n
    memo(k) = memo(k-1) + memo(k-2);
end
f = memo(n);
end
call number 1
call number 2
call number 3
fib(30) = 832040
fib(50) = 12586269025

clear functions (or clear all) resets persistent variables.

global variables

A global variable is shared by every workspace that declares it with global name. It works, but it makes code hard to follow and test, because any function can change it. Prefer passing values as arguments or grouping settings in a struct.

matlab · try it yourself
global UNITS
UNITS = 'metric';
describe_units();
UNITS = 'imperial';
describe_units();

function describe_units()
global UNITS
fprintf('Using %s units\n', UNITS);
end
Using metric units
Using imperial units

Both the script and the function must declare global UNITS; without the declaration inside the function, UNITS would be an unknown local variable there.

Nested functions (function files only)

In a function file (not a script), a function can be defined inside another, before its end. A nested function shares the variables of its parent:

matlab
function total = shopping_total(prices)
    total = 0;
    for p = prices
        add(p);
    end
    function add(amount)       % nested: sees and changes 'total'
        total = total + amount;
    end
end

Nested functions are powerful but easy to overuse: shared variables make code harder to follow. Octave 11 supports them in function files too (including handles to nested functions that keep their state), but local functions with explicit arguments are usually the clearer choice. See Local & Nested Functions.

Test yourself

A script sets n = 5 and calls f(), where f is a function that doesn't take inputs. Can f read n?

  1. Yes, always
  2. No, functions have their own workspace
  3. Only if n is a loop variable
  4. Only in Octave

What is the value of k after for k = 1:4, end?

  1. Undefined
  2. 1
  3. 4
  4. 5

What value does a persistent variable have on the first call?

  1. 0
  2. An empty matrix []
  3. NaN
  4. It is an error to read it