Skip to Main Content Skip to Search
Product Documentation

Parameterizing Functions

Using Nested Functions

One way to provide additional parameters to a functional argument of a function function is to write a file that

The following example illustrates how to find a zero of the cubic polynomial x3 + bx + c, for different values of the coefficients b and c, using this method. To do so, write a file with the following code:

function y = findzero(b, c, x0)

options = optimset('Display', 'off'); % Turn off Display
y = fzero(@poly, x0, options);

	function y = poly(x) % Compute the polynomial.
	y = x^3 + b*x + c;
	end
end

The main function, findzero, does two things:

You can call findzero with any values of the coefficients b and c, which are seen by poly because it is a nested function.

As an example, to find a zero of the polynomial with b = 2 and c = 3.5, using the starting point x0 = 0, call findzero as follows.

x = findzero(2, 3.5, 0)

This returns the zero

x =

   -1.0945

Using Anonymous Functions

Suppose you have already written a standalone file for the function poly containing the following code, which computes the polynomial for any coefficients b and c,

function y = poly(x, b, c) % Compute the polynomial.
y = x^3 + b*x + c;

You then want to find a zero for the coefficient values b = 2 and c = 3.5. You cannot simply apply fzero to poly, which has three input arguments, because fzero only accepts functions with a single input argument.

As an alternative to rewriting poly as a nested function (see Using Nested Functions) you can pass poly to fzero as a function handle to an anonymous function that has the form @(x) poly(x, b, c). The function handle has just one input argument x, so fzero accepts it.

b = 2;
c = 3.5;
x = fzero(@(x) poly(x, b, c), 0)

This returns the zero

x =

   -1.0945

Anonymous Functions explains how to create anonymous functions.

If you later decide to find a zero for different values of b and c, you must redefine the anonymous function using the new values. For example,

b = 4;
c = -1;
fzero(@(x) poly(x, b, c), 0)

ans =

    0.2463

For more complicated objective functions, it is usually preferable to write the function as a nested function.

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS