CSE 1121
Scientific Programming
ENGR 101
Introduction to Programming
User Defined Functions
Creating Function M-files
• User defined functions are stored as separate M-
files
• To use them, they must be in the current directory
Syntax
• All functions have a similar syntax, whether they
are built-in functions or user-defined functions
• Name
• Input
• Output
A=cos(x)
User-defined functions must start with a
function definition line
• The line contains…
• The word ‘function’
• A variable that defines the function output
• A function name
•
function output = poly(x)
A simple function
The function name must be the same as the
file name
The function is available from
the command window or from
other M-file programs
Function using the Toolbar
Open MATLAB. Open a new Function File.
The Function File consists of a beginning and end which is outlined on the left of the
function. This function will be used to calculate the volume of a sphere:
The radius of th sphere will be an input argument, and the volume of the sphere will
be an output variable. Double-click on input args and replace it with
Sphere_Radius. Double-click on output args and replace it with Sphere_Volume.
Press the Save button. This will automatically name the
Function File appropriately.
Type in the equation for the volume of a sphere as shown below.
You must use the input variable name Sphere_Radiusand the
output variable name Sphere_Volumeas specified in the Function
Statement. Make sure to Save the Function File whenever you
make changes to it.
Hint
Functions with Multiple Inputs
and Outputs
• Recall the remainder function
This function has two
inputs
A user defined function with
multiple inputs
Functions with Multiple Outputs
• Recall the max
function
• It returns two
results
This function return 3
output values
If you don’t ask for
all three results, the
program just
returns the first
value
Recall the size function
At first this
function looks
like it returns
two values –
but it really
only returns a
single array
with two
elements
Functions with no input or no
output
• It isn’t always necessary to define an output
No output is defined
Just because a function does not
return an output value doesn’t mean
it doesn’t do anything. This function
draws a star
When you try to set
the star function
equal to a variable,
an error statement
is returned
Determining the number of
input and output arguments
• nargin
• determines the number of input arguments
• nargout
• determines the number of output arguments
The input to these functions is
represented using a string
You can use these functions in your
programming to make your functions
more versatile
• For example the surf function accepts a variable
number of arguments
• surf(z) plots the 2-D matrix z against the index
numbers
• surf(x,y,z) plots the 2-D matrix z against the x and y
coordinates
When a variable number of
arguments is allowed…
• nargin returns -1
Checks to see how
many output values
… and the output is
were requested
stored in the
workspace
If star1 is not set equal to a
variable the star is drawn
but no output is returned
If star1 is set
equal to a
variable, the
rhyme is
returned
Local Variables
• Variables defined in an M-file function, only have
meaning inside that program
• if I set x=1 in the command window, it is not equal
to 1 in the function
• If I set y=2 in a function, it is not equal to 2 in the
workspace window
• The only way to communicate between functions
and the workspace, is through the function input
and output arguments
in this case ans
is the only
variable created
x, y, a, and output are
local variables to the g
function
When the g function is executed, the
only variable created is determined in
the command window (or script M-file
used to execute a program)
g must be defined in the function file
Even though
If you don’t define g in this function, g is
it won’t
work!! defined in the
workspace, the
function can’t
access it
Global Variables
• Although it is possible to define global variables
In general, It is a bad idea!!
• Need to define in function m file and in command
window or m file
Accessing M-file Code
• functions provided with MATLAB consist of two
types
• The first is built in, and the code is not accessible to us
• The second type consists of groups of function M-files –
just like the ones we’ve been writing
• Use the type function to see the code in
function M-files
The sphere function is stored as a
function M-file, but is provided by
MATLAB. Studying these functions
may help you understand how to
program better functions yourself
We just wrote this function, and saved it into
the current directory.
Set path for your functions
Anonymous Functions
• Normally if you go to the trouble of creating a
function, you want to store it for future use.
• Anonymous functions are defined inside a script M-
file or in the command window, and are only
available while they are stored in the workspace
window – much like variables
Define anonymous
functions in a script M-file
• Suppose you’d like to define a function for natural
log called ln
• ln=@(x) log(x)
• The @ symbol alerts MATLAB that ln is a function
• The function input is next, inside parentheses
• Finally the function is defined
function definition
The name of the function is called a
function handle – in this case it is ln
Notice that function handles are
represented with the box symbol in
the workspace window
Saving Anonymous Functions
• Anonymous functions can be saved as a .mat file –
just like anything else listed in the workspace
window
• Retrieve anonymous functions using the load
command
Function Handles
• Function Handle, which is used to reference a User-
Defined Function.
• It is possible to assign a function handle to any
user-defined function, including those stored in m-
files
• If an m-file called distance is stored in the current
directory then.
• d = @distance;
MATLAB documentation for Function
Handle
MATLAB documentation for Function
Handle
Why would you want to do this?
• Function handles make using functions as an input of a
different function easier
You can pass the function as an argument to another
function. For example, we can plot the function over 0 £ x £
6 as follows:
f1=@(x) x + 2*exp(-x) - 3
>>fplot(f1,[1 50])
Function Functions
• Some functions accept other functions as input
• An example is the fplot function described in
chapter 5 or the nargin and nargout functions
described in this chapter
Either syntax gives
the same result
fplot requires a function in the
first input field
Function functions can also accept a
function handle in place of the
function itself – in this case ln
Here’s another example where a function
handle is assigned to a more complicated
expression.
It’s easier to use poly5 in the fplot command,
than to type in the whole polynomial
We can use the function handle again in
the fzero function function, which finds
the value of x when the function equals
zero
Finding the Minimum of a Function
The fminbnd function finds the minimum of a function
of a single variable, which is denoted by x. One form of
its syntax is
fminbnd(@function, x1, x2)
where @function is the function handle for the
function. The fminbnd function returns a value of x that
minimizes the function in the interval x1 ≤ x ≤ x2.
For example, fminbnd(@cos,0,4) returns the value
3.1416.
When using fminbnd it is more convenient to define the
function in a function file. For example, if y = 1 - xe -x ,
define the following function file:
function y = f2(x)
y = 1-x.*exp(-x);
To find the value of x that gives a minimum of y for 0 £ x
£ 5, type
>>x = fminbnd(@f2,0,5)
The answer is x = 1. To find the minimum value of y, type
y = f2(x). The result is y = 0.6321.
A function can have one or more local minima
and a global minimum.
If the specified range of the independent variable
does not enclose the global minimum, fminbnd
will not find the global minimum.
fminbnd will find a minimum that occurs on a
boundary.
Plot of the function y = 0.025x 5 - 0.0625x 4 - 0.333x 3 + x 2.
This function
has one local
and one
global
minimum.
On the
interval [1, 4]
the minimum
is at the
boundary, x
= 1.
2 2
To minimize the function f = xe-x - y , we first define it in
an M-file, using the vector x whose elements are x(1) =
x and x(2) = y.
function f = f4(x)
f = x(1).*exp(-x(1).^2-x(2).^2);
Suppose we guess that the minimum is near x = y = 0.
The session is
>>fminsearch(@f4,[0,0])
ans =
-0.7071 0.000
Thus the minimum occurs at x = -0.7071, y = 0.
Subfunctions
• More complicated functions can be created by
grouping functions together into a single file, as
subfunctions
• Each MATLAB function m-file has one primary
function
• Subfunctions are added to the primary function,
and can have any legitimate MATLAB name