15.11.2014 Views

MATLAB Mathematics - SERC - Index of

MATLAB Mathematics - SERC - Index of

MATLAB Mathematics - SERC - Index of

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

4 Function Functions<br />

Parameterizing Functions Called by Function Functions<br />

At times, you might want use a function function that calls a function with<br />

several parameters. For example, if you want to use fzero to find zeros <strong>of</strong> the<br />

cubic polynomial x 3 + bx + c for different values <strong>of</strong> the coefficients b and c,<br />

you would like the function that computes the polynomial to accept the<br />

additional parameters b and c. When you invoke fzero, you must also provide<br />

values for these additional parameters to the polynomial function. This section<br />

describes two ways to do this:<br />

• “Providing Parameter Values Using Nested Functions” on page 4-30<br />

• “Providing Parameter Values to Anonymous Functions” on page 4-31<br />

Providing Parameter Values Using Nested Functions<br />

One way to provide parameters to the polynomial is to write a single M-file that<br />

• Accepts the additional parameters as inputs<br />

• Invokes the function function<br />

• Contains the function called by the function function as a nested function<br />

The following example illustrates how to find a zero <strong>of</strong> the cubic polynomial<br />

x 3 + bx + c, for different values <strong>of</strong> the coefficients b and c, using this method.<br />

To do so, write an M-file with the following code.<br />

function y = findzero(b, c, x0)<br />

options = optimset('Display', '<strong>of</strong>f'); % Turn <strong>of</strong>f Display<br />

y = fzero(@poly, x0, options);<br />

function y = poly(x) % Compute the polynomial.<br />

y = x^3 + b*x + c;<br />

end<br />

end<br />

The main function, findzero, does two things:<br />

• Invokes the function fzero to find a zero <strong>of</strong> the polynomial<br />

• Computes the polynomial in a nested function, poly, which is called by fzero<br />

4-30

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

Saved successfully!

Ooh no, something went wrong!