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.

Representing Functions in <strong>MATLAB</strong><br />

Representing Functions in <strong>MATLAB</strong><br />

<strong>MATLAB</strong> can represent mathematical functions by expressing them as<br />

<strong>MATLAB</strong> functions in M-files or as anonymous functions. For example,<br />

consider the function<br />

1<br />

fx ( ) = ------------------------------------------<br />

( x – 0.3) 2 + 0.01<br />

1<br />

+ ------------------------------------------<br />

( x – 0.9) 2 – 6<br />

+ 0.04<br />

This function can be used as input to any <strong>of</strong> the function functions.<br />

<strong>MATLAB</strong> Functions<br />

You can find the function above in the M-file named humps.m.<br />

function y = humps(x)<br />

y = 1./((x - 0.3).^2 + 0.01) + 1./((x - 0.9).^2 + 0.04) - 6;<br />

To evaluate the function humps at 2.0, use @ to obtain a function handle for<br />

humps, and then use the function handle in the same way you would use a<br />

function name to call the function:<br />

fh = @humps;<br />

fh(2.0)<br />

ans =<br />

-4.8552<br />

Anonymous Functions<br />

A second way to represent a mathematical function at the command line is by<br />

creating an anonymous function from a string expression. For example, you<br />

can create an anonymous function <strong>of</strong> the humps function. The value returned,<br />

fh, is a function handle:<br />

fh = @(x)1./((x-0.3).^2 + 0.01) + 1./((x-0.9).^2 + 0.04)-6;<br />

You can then evaluate fh at 2.0 in the same way that you can with a function<br />

handle for a <strong>MATLAB</strong> function:<br />

fh(2.0)<br />

ans =<br />

-4.8552<br />

4-3

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

Saved successfully!

Ooh no, something went wrong!