
4 Programming
and output arguments involved in each particular use of the function. The
rank function uses nargin, but does not need to use nargout.
Types of Functions
MATLAB offers several different types of functions to use in your
programming.
Anonymous Functions
An anonym ous function is a simple form of M ATLAB function that does not
require an M-file. It consists of a single MATLAB expression and any number
of input and output arguments. You can define an anonymo us func tion right
at the MATLAB command line, or within an M-file function or script. This
gives you a quick means of creating simple functions without having to create
M-files each time.
The syntax for creating an anonymous function from an expression is
f = @(arglist)express ion
The statement below creates an anonymous function that finds the square of
a number. When you call this function, MATLAB assigns the value you pass
in to variable
x,andthenusesx in th e equation x.^2:
sqr = @(x) x.^ 2;
To execute the sqr function defined above, type
a = sqr(5)
a=
25
Primary and Subfunctions
All functions that are not anonymous must be defined within an M-file. Each
M-file has a required primary function that a ppears first in the file, and any
number of subfunctions that follow the p rim ary. Primary functions have a
wider scope than subfunctions. That is, primary functions can be invoked from
outside of their M-fi le (from the MATLAB command line or from functions in
4-24
Commenti su questo manuale