MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1
X = [1,2,3];
Y = update1(X)

Y =
3 5 7

Nested Functions


A nested function has access to the workspaces of all functions in which it is nested. So,
for example, a nested function can use a variable (in this case, x) that is defined in its
parent function:

function primaryFx
x = 1;
nestedFx

function nestedFx
x = x + 1;
end
end

When parent functions do not use a given variable, the variable remains local to the
nested function. For example, in this version of primaryFx, the two nested functions
have their own versions of x that cannot interact with each other.

function primaryFx
nestedFx1
nestedFx2

function nestedFx1
x = 1;
end

function nestedFx2
x = 2;
end
end

For more information, see “Nested Functions” on page 20-32.

Persistent Variables


When you declare a variable within a function as persistent, the variable retains its value
from one function call to the next. Other local variables retain their value only during the

20 Function Basics

Free download pdf