15.11.2014 Views

MATLAB Mathematics - SERC - Index of

MATLAB Mathematics - SERC - Index of

MATLAB Mathematics - SERC - Index of

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Minimizing Functions and Finding Zeros<br />

Example <strong>of</strong> a Nested Output Function<br />

The example in “Creating and Using an Output Function” on page 4-15 does<br />

not require the output function to preserve data from one iteration to the next.<br />

When this is the case, you can write the output function as an M-file and call<br />

the optimization function directly from the command line. However, if you<br />

want your output function to record data from one iteration to the next, you<br />

should write a single M-file that does the following:<br />

• Contains the output function as a nested function — see Nested Functions in<br />

the online <strong>MATLAB</strong> documentation for more information.<br />

• Calls the optimization function.<br />

In the following example, the M-file also contains the objective function as a<br />

subfunction, although you could also write the objective function as a separate<br />

M-file or as an anonymous function.<br />

Since the nested function has access to variables in the M-file function that<br />

contains it, this method enables the output function to preserve variables from<br />

one iteration to the next.<br />

The following example uses an output function to record the points generated<br />

by fminsearch in solving the optimization problem<br />

minimize<br />

x<br />

fx ( ) e x 1 2 2<br />

= ( 4x 1 + 2x 2 + 4x 1 x 2 + 2x 2 + 1)<br />

and returns the sequence <strong>of</strong> points as a matrix called history.<br />

To run the example, do the following steps:<br />

1 Open a new M-file in the <strong>MATLAB</strong> editor.<br />

2 Copy and paste the following code into the M-file.<br />

function [x fval history] = myproblem(x0)<br />

history = [];<br />

options = optimset('OutputFcn', @myoutput);<br />

[x fval] = fminsearch(@objfun, x0,options);<br />

4-17

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

Saved successfully!

Ooh no, something went wrong!