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.

4 Function Functions<br />

To try fminsearch, create a function three_var <strong>of</strong> three variables, x, y, and z.<br />

function b = three_var(v)<br />

x = v(1);<br />

y = v(2);<br />

z = v(3);<br />

b = x.^2 + 2.5*sin(y) - z^2*x^2*y^2;<br />

Now find a minimum for this function using x = -0.6, y = -1.2, and<br />

z = 0.135 as the starting values.<br />

v = [-0.6 -1.2 0.135];<br />

a = fminsearch(@three_var,v)<br />

a =<br />

0.0000 -1.5708 0.1803<br />

Fitting a Curve to Data<br />

This section gives an example that shows how to fit an exponential function <strong>of</strong><br />

the form Ae – λt<br />

to some data. The example uses the function fminsearch to<br />

minimize the sum <strong>of</strong> squares <strong>of</strong> errors between the data and an exponential<br />

function Ae – λt<br />

for varying parameters A and λ. This section covers the<br />

following topics.<br />

• “Creating an M-file for the Example” on page 4-10<br />

• “Running the Example” on page 4-11<br />

• “Plotting the Results” on page 4-12<br />

Creating an M-file for the Example<br />

To run the example, first create an M-file that<br />

• Accepts vectors corresponding to the x- and y-coordinates <strong>of</strong> the data<br />

• Returns the parameters <strong>of</strong> the exponential function that best fits the data<br />

To do so, copy and paste the following code into an M-file and save it as<br />

fitcurvedemo in a directory on the <strong>MATLAB</strong> path.<br />

function [estimates, model] = fitcurvedemo(xdata, ydata)<br />

% Call fminsearch with a random starting point.<br />

start_point = rand(1, 2);<br />

4-10

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

Saved successfully!

Ooh no, something went wrong!