Mathematics | ![]() ![]() |
Representing Functions in MATLAB
MATLAB can represent mathematical functions by expressing them as MATLAB functions in M-files or as inline objects. For example, consider the function
This function can be used as input to any of the function functions.
As MATLAB Functions
You can find the function above in the M-file named humps.m
.
function y = humps(x) y = 1./((x - 0.3).^2 + 0.01) + 1./((x - 0.9).^2 + 0.04) - 6;
To evaluate the function humps
at 2.0, use @
to obtain a function handle for humps
, and then pass the function handle to feval
.
fh = @humps; feval(fh,2.0) ans = -4.8552
As Inline Objects
A second way to represent a mathematical function at the command line is by creating an inline object from a string expression. For example, you can create an inline object of the humps
function
f = inline(`1./((x-0.3).^2 + 0.01) + 1./((x-0.9).^2 + 0.04)-6');
You can then evaluate f
at 2.0
.
f(2.0) ans = -4.8552
You can also create functions of more than one argument with inline
by specifying the names of the input arguments along with the string expression. For example, the following function has two input arguments x
and y
.
f= inline('y*sin(x)+x*cos(y)','x','y') f(pi,2*pi) ans = 3.1416
All of the functions described in this chapter are called function functions because they accept, as one of their arguments, either a function handle to a function like humps
or an inline object that defines a mathematical function.
Note
For information about function handles, see the function_handle (@), func2str , and str2func reference pages, and the Function Handles section of "Programming and Data Types" in the MATLAB documentation.
|
![]() | Function Summary | Plotting Mathematical Functions | ![]() |