y = x + 1;
end
end
Using Handles to Store Function Parameters
Nested functions can use variables from three sources:
• Input arguments
• Variables defined within the nested function
• Variables defined in a parent function, also called externally scoped variables
When you create a function handle for a nested function, that handle stores not only the name of the
function, but also the values of externally scoped variables.
For example, create a function in a file named makeParabola.m. This function accepts several
polynomial coefficients, and returns a handle to a nested function that calculates the value of that
polynomial.
function p = makeParabola(a,b,c)
p = @parabola;
function y = parabola(x)
y = a*x.^2 + b*x + c;
end
end
The makeParabola function returns a handle to the parabola function that includes values for
coefficients a, b, and c.
At the command line, call the makeParabola function with coefficient values of 1.3, .2, and 30. Use
the returned function handle p to evaluate the polynomial at a particular point:
p = makeParabola(1.3,.2,30);
X = 25;
Y = p(X)
Y =
847.5000
Many MATLAB functions accept function handle inputs to evaluate functions over a range of values.
For example, plot the parabolic equation from -25 to +25:
fplot(p,[-25,25])
Nested Functions
20-29
end
end
Using Handles to Store Function Parameters
Nested functions can use variables from three sources:
• Input arguments
• Variables defined within the nested function
• Variables defined in a parent function, also called externally scoped variables
When you create a function handle for a nested function, that handle stores not only the name of the
function, but also the values of externally scoped variables.
For example, create a function in a file named makeParabola.m. This function accepts several
polynomial coefficients, and returns a handle to a nested function that calculates the value of that
polynomial.
function p = makeParabola(a,b,c)
p = @parabola;
function y = parabola(x)
y = a*x.^2 + b*x + c;
end
end
The makeParabola function returns a handle to the parabola function that includes values for
coefficients a, b, and c.
At the command line, call the makeParabola function with coefficient values of 1.3, .2, and 30. Use
the returned function handle p to evaluate the polynomial at a particular point:
p = makeParabola(1.3,.2,30);
X = 25;
Y = p(X)
Y =
847.5000
Many MATLAB functions accept function handle inputs to evaluate functions over a range of values.
For example, plot the parabolic equation from -25 to +25:
fplot(p,[-25,25])
Nested Functions
20-29
