MATLAB: Lexical scoping and namespaces

lexical scoping namespacesMATLABnested functions

This code…
function [] = foo()
bar();
baz();
function [] = bar()
a = 1;
end
function [] = baz()
if a
fprintf('Foo!\n');
end
end
end
…gives me this error…
Undefined function or variable 'a'.
Error in foo/baz (line 12)
if a
Error in foo (line 5)
baz();
…but this code…
function [] = foo()
bar();
a;
baz();
function [] = bar()
a = 1;
end
function [] = baz()
if a
fprintf('Foo!\n');
end
end
end
…gives me…
Foo!
Please explain what is going on here. Is there any documentation for this behavior? I would appreciate any documentation which can help me better understand Matlab's lexical scoping rules, and how symbols are imported into certain namespaces.
Thanks.

Best Answer

From the documentation,
" As a rule, a variable used or defined within a nested function resides in the workspace of the outermost function that both contains the nested function and accesses that variable. "
and
" Like other functions, a nested function has its own workspace. But it also has access to the workspaces of all functions in which it is nested. "
So in the second example, the variable 'a' exists within the outer function's (foo's) workspace because the outer function both contains the nested function (bar) that defines it and accesses the variable. In the first example, only one criterion is met - the outer function does not access the variable. Since the outermost function (foo) does not access the variable, the variable is not in it's workspace.
Now the second nested function (baz) has access to all variables defined within it's own workspace along with those other variables that are either used by or defined in the outer function's workspace. In the first example the variable 'a' is neither, so baz has no access to it.
Related Question