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.

Minimizing Functions and Finding Zeros<br />

Creating and Using an Output Function<br />

The following is a simple example <strong>of</strong> an output function that plots the points<br />

generated by an optimization function.<br />

function stop = outfun(x, optimValues, state)<br />

stop = false;<br />

hold on;<br />

plot(x(1),x(2),'.');<br />

drawnow<br />

You can use this output function to plot the points generated by fminsearch in<br />

solving the optimization problem<br />

minimize<br />

x<br />

fx ( ) e x1 2 2<br />

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

To do so,<br />

1 Create an M-file containing the preceding code and save it as outfun.m in a<br />

directory on the <strong>MATLAB</strong> path.<br />

2 Enter the command<br />

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

to set the value <strong>of</strong> the Outputfcn field <strong>of</strong> the options structure to a function<br />

handle to outfun.<br />

3 Enter the following commands:<br />

hold on<br />

objfun=@(x) exp(x(1))*(4*x(1)^2+2*x(2)^2+x(1)*x(2)+2*x(2));<br />

[x fval] = fminsearch(objfun, [-1 1], options)<br />

hold <strong>of</strong>f<br />

This returns the solution<br />

x =<br />

0.1290 -0.5323<br />

fval =<br />

-0.5689<br />

4-15

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

Saved successfully!

Ooh no, something went wrong!