23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Nested Functions<br />

Variable Scope in Nested Functions<br />

The scope of a variable is the range of functions that have direct access to the<br />

variable to set, modify, or acquire its value. When you define a local (i.e.,<br />

nonglobal) variable within a function, its scope is normally restricted to that<br />

function alone. For example, subfunctions do not share variables with the<br />

primary function or with other subfunctions. This is because each function<br />

and subfunction stores its variables in its own separate workspace.<br />

Like other functions, a nested function has its own workspace. But it also has<br />

access to the workspaces of all functions in which it is nested. So, for example,<br />

a variable that has a value assigned to it by the primary function can be read<br />

or overwritten by a function nested at any level within the primary. Similarly,<br />

a variable that is assigned in a nested function can be read or overwritten by<br />

any of the functions containing that function.<br />

In the following two examples, variable x is stored in the workspace of the<br />

outer varScope function and can be read or written to by all functions nested<br />

within it.<br />

function varScope1<br />

x = 5;<br />

nestfun1<br />

function nestfun1<br />

nestfun2<br />

function nestfun2<br />

x = x + 1<br />

end<br />

end<br />

end<br />

function varScope2<br />

nestfun1<br />

function nestfun1<br />

nestfun2<br />

function nestfun2<br />

x = 5;<br />

end<br />

end<br />

x = x + 1<br />

end<br />

As a rule, a variable used or defined within a nested function resides in the<br />

workspace of the outermost function that both contains the nested function<br />

and accesses that variable. The scope of this variable is then the function to<br />

which this workspace belongs, and all functions nested to any level within<br />

that function.<br />

In the next example, the outer function, varScope3, does not access variable x.<br />

Following the rule just stated, x is unknown to the outer function and thus is<br />

5-19

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!