MATLAB
Functions – Part II
Greg Reese, Ph.D
Research Computing Support Group
Academic Technology Services
Miami University
September 2013
MATLAB
Functions – Part II
© 2010-2013 Greg Reese. All rights reserved
2
Part I
• Write scripts
• Run MATLAB functions
• Write and run our own functions
• Use our functions in MATLAB
plotting and optimization routines
• Write and use anonymous
functions
3
Part II
• Document functions
• Detect number of inputs and outputs
• Subfunctions
• Nested functions
4
Documentation
5
Documentation
To find out how to use a MATLAB function you
type the command
help function_name
If you don't know function name, can look for
important word in function description with
lookfor word
We can incorporate our functions in the
MATLAB help system so help and lookfor
work on custom code
6
Documentation
Look at results for MATLAB csvread()
Try It
1. Type help csvread
2. Type lookfor 'comma separated'
3. Type type csvread
7
Documentation
>> help csvread
CSVREAD Read a comma separated value file.
M = CSVREAD('FILENAME') reads a comma separated value formatted file
FILENAME. The result is returned in M. The file can only contain
numeric values.
M = CSVREAD('FILENAME',R,C) reads data from the comma separated value, etc.
>> lookfor 'comma separated'
lists
- Comma separated lists.
csvread
- Read a comma separated value file.
csvwrite
- Write a comma separated value file.
>> type csvread
function m = csvread(filename, r, c, rng)
%CSVREAD Read a comma separated value file.
%
M = CSVREAD('FILENAME') reads a comma separated value formatted file
%
FILENAME. The result is returned in M. The file can only contain
%
numeric values.
%
%
M = CSVREAD('FILENAME',R,C) reads data from the comma separated value
etc.
8
Documentation
help displays first group of
contiguous comment lines in file
• Traditionally put right after function line
• Blank line breaks contiguous group
– To display blank, put in line with only a
percent sign
9
Documentation
Example – help output
In file doc_check.m
function [ result details ] = doc_check( fileName )
% DOC_CHECK Check a function m-file for correct documentation.
%
% Check that first comment has function name in capital letters and line
% ends with a period, that every input and output parameter is documented,
% etc. See explanation for "details" output parameter for full list
>> help doc_check
DOC_CHECK Check a function m-file for correct documentation.
Check that first comment has function name in capital letters and line
ends with a period, that every input and output parameter is documented,
etc. See explanation for "details" output parameter for full list
10
Documentation
H1 or description line
• H1 = first line in help description
• lookfor uses this line
– Make line descriptive of function
– Include words user would most likely
search for
11
Documentation
Example – lookfor output
In file doc_check.m
function [ result details ] = doc_check( fileName )
% DOC_CHECK Check a function m-file for correct documentation
>> lookfor documentation
doc_check - Check a function m-file for correct documentation.
builddocsearchdb - Build documentation search database
doc - Display HTML documentation in the Help browser.
docsearch - Search HTML documentation in the Help browser.
12
Documentation
Suggestions for documentation
• H1 line
• Longer description of functionality
• Description of parameters
• Description of errors and how they're
handled
• References
13
Documentation
H1 line suggestions
• File name in caps*
• End in period*
• Contain words likely to be searched for
* MATLAB conventions. Don't know if they have functionality
14
Documentation
Longer description suggestions
• Name of algorithm, inputs and outputs,
e.g. "Run's Reese's algorithm on the
students in the class and produces a list
of slackers and hard workers"
• Don't put in details spelled out further in
documentation
15
Documentation
Parameter suggestions
• Definition
• Data type, e.g., scalar, vector, matrix, etc.
– For vector, whether row, column or either
• Units
• Range
– Be careful with > and ≥
• Optional or required
– Default if optional input
16
Documentation
Error suggestions
• Conditions that cause error
• State of output if error
• Internal state if error, e.g., "All open files in
routine will be closed if there is an error"
• Error reporting mechanism
– error()
– errordlg()
– Text of message
17
Documentation
Example
In file doc_check.m
function [ result details ] = doc_check( fileName )
% DOC_CHECK Check a function m-file for correct documentation.
%
% Check that first comment has function name in capital letters and line
% ends with a period, that every input and output parameter is documented,
% etc. See explanation for "details" output parameter for full list
%
% REQUIRED INPUT
% fileName - name of file to check
% REQUIRED OUTPUT
% result - true if all items checked for are correct, false otherwise
% OPTIONAL OUTPUT
% details - all values true or false
% details(1) - first word of first comment line is function name in caps
% details(2) - first comment line ends with a period
% etc.
% ERRORS
% If can't open or read file, calls error()
fid = fopen( fileName );
% etc.
18
Documentation
Example - errors
Output for
help doc_check.m
>> help doc_check
DOC_CHECK Check a function m-file for correct documentation.
Check that first comment has function name in capital letters and line
ends with a period, that every input and output parameter is documented,
etc. See explanation for "details" output parameter for full list
REQUIRED INPUT
fileName - name of file to check
REQUIRED OUTPUT
result - true if all items checked for are correct, false otherwise
OPTIONAL OUTPUT
details - all values true or false
details(1) - first word of first comment line is function name in caps
details(2) - first comment line ends with a period
etc.
ERRORS
If can't open or read file, calls error()
19
Documentation
References
• Full citations for books, papers, etc.
• Web sites
– URL
– Date downloaded
• External codes used
– MATLAB central
– sourceforge.net
– university
20
Documentation
Questions?
21
Input / Output
Arguments
22
Arguments
One function can have different numbers of
inputs or outputs. Most MATLAB functions
are like this
fminbnd
Find minimum of single-variable function on fixed interval
Syntax
x = fminbnd(fun,x1,x2)
x = fminbnd(fun,x1,x2,options)
[x,fval] = fminbnd(...)
[x,fval,exitflag] = fminbnd(...)
[x,fval,exitflag,output] = fminbnd(...)
23
Arguments
Why different number of inputs?
• Save caller from always entering argument that
has commonly used value
– e.g., delimiter in tokenizer usually a space
• Save caller from entering redundant arguments
– e.g., correlation( x, y ) computes cross-correlation, for
autocorrelation want correlation( x ) instead of
correlation( x, x )
• Allow caller to enter extra information if available
– e.g., pass graph title to plotting routine
24
Arguments
In a function, get number of arguments
passed to function with nargin
Example – download scale.m
function [ y expansion ] = scale( x, m, b )
% SCALE - linearly scale x so that y = m*x + b
% x - unscaled data, row or column vector
% Optional input arguments
% m - slope, scalar ~= 0, default = 1
% b - y-intercept, scalar, default = 0
%
% Required output
% y - scaled data, same dimensions as x
% Optional output
% expansion - optional output, scalar,
%
expansion = (yMax-yMin)/(xMax-xMin)
25
Arguments
Typical verification of number of inputs
function [ y expansion ] = scale( x, m, b )
% verify right number of input arguments
if nargin == 1
m = 1;
b = 0;
elseif nargin == 2
If missing inputs, set them
b = 0;
If not max number of inputs, bail out
elseif nargin ~= 3
error( 'USAGE: y = scale( x, m, b )
m, b optional' );
end
26
Arguments
Can verify data type
% verify data type
if ~isvector( x )
error( 'x must be a vector' );
elseif ~isscalar( m ) | ~isscalar( b )
error( 'm and b must be scalars' );
end
27
Arguments
Can verify range
%verify range
if m == 0
error( 'm must not be zero' );
end
28
Arguments
Try It
>> y = scale( magic(3) )
??? Error using ==> scale at 23
x must be a vector
>> y = scale( 1:5, 2 )
y =
2
4
6
8
10
>> y = scale( 1:5, 2, [ 5 6] )
??? Error using ==> scale at 25
m and b must be scalars
>> y = scale( 1:5, 2, 1, 5 )
??? Error using ==> scale
Too many input arguments.
>> y = scale( 1:5, 2, 1 )
y =
3
5
7
9
11
29
Arguments
Why different number of outputs?
• Provide caller with less important
computations
– e.g., [R,P]=corrcoef(...) can return main
result R (correlation coefficients) and optionally
P (p-values)
• Provide caller with information about
processing that took place
• Provide caller with information for use with
other functions
• Provide caller with information about any
errors
30
Main results
Arguments
Example – MATLAB fminbnd()
[x,fval] = fminbnd(...) returns the value of the objective function computed in
fun at x.
Exit status
[x,fval,exitflag] = fminbnd(...) returns a value exitflag that describes the exit
condition of fminbnd:
1
fminbnd converged to a solution x based on options.TolX.
0
Maximum number of function evaluations or iterations was reached.
-1
Algorithm was terminated by the output function.
-2
Bounds are inconsistent (x1 > x2).
[x,fval,exitflag,output] = fminbnd(...) returns a structure output that contains
Processing information
information about the optimization:
output.algorithm
Algorithm used
output.funcCount
Number of function evaluations
output.iterations
Number of iterations
output.message
Exit message
31
Arguments
In a function, get number of arguments
requested by caller with nargout
Example – scale.m
function [ y expansion ] = scale( x, m, b )
% SCALE - linearly scale x so that y = m*x + b
% x - unscaled data, row or column vector
% Optional input arguments
% m - slope, scalar ~= 0, default = 1
% b - y-intercept, scalar, default = 0
%
% Required output
% y - scaled data, same dimensions as x
% Optional output
% expansion - optional output, scalar,
%
expansion = (yMax-yMin)/(xMax-xMin)
32
Arguments
Processing different number of outputs
function [ y expansion ] = scale( x, m, b )
% compute main output
if nargout == 1
y = m * x + b;
If optional output desired,
elseif nargout == 2
compute it
y = m * x + b;
expansion = ( max(y) - min(y) ) / ( max(x) - min(x) );
else
If not max number of inputs, bail out
error( 'USAGE: [ y expansion ] = scale( x, m, b )
m, b
optional' );
end
33
Arguments
Try It
>> scale( 1:5 )
??? Error using ==> scale at 42
USAGE: [ y expansion ] = scale( x, m, b )
>> y = scale( 1:5 )
y =
1
2
3
4
5
>> y = scale( 1:5, 3 )
y =
3
6
9
12
15
>> [ y ratio ] = scale( 1:5, 3 )
y =
3
6
9
12
15
ratio =
3
>> [ y ratio z ] = scale( 1:5, 3 )
??? Error using ==> scale
Too many output arguments.
m, b optional
34
Arguments
Questions?
35
Subfunctions
36
Subfunctions
A function m-file can contain more than one
function. All functions other that the first one
are called subfunctions.
Subfunctions
–Used mainly to carry out tasks that should be
separated from primary function but unlikely to be used
by other m-files
– Help avoid having a lot of m-files
– Override (used in place of) other functions of same
name
37
Subfunctions
Subfunctions in a file
• Start with a function line
• End at next function line or at end of file
• Are only visible (usable) by the primary
function or the other subfunctions
• Can come in any order as long as
primary function comes first
• Cannot access variables in other
subfunctions or in the primary function
38
Subfunctions
Example – download newstats.m
function [avg, med] = newstats(u) % Primary function
% NEWSTATS Find mean and median with internal functions.
% From MATLAB help on subfunction
n = length(u);
% Note subfunction mean() gets called, not MATLAB's mean()
avg = mean(u, n);
med = my_median(u, n);
function a = mean(v, n)
% Subfunction
% Calculate average.
a = sum(v)/n;
function m = my_median(v, n)
% Subfunction
% Calculate median.
w = sort(v);
if rem(n, 2) == 1
m = w((n+1) / 2);
else
m = (w(n/2) + w(n/2+1)) / 2;
end
39
Subfunctions
Try It
Call primary function
>> [ av med ] = newstats( 1:11 )
av = 6
med = 6
Call subfunction
>> med2 = my_median( 1:11, 11 )
??? Undefined function or method 'my_median' for
input arguments of type 'double'.
40
Subfunctions
Try It
Verify overridden mean()called by putting line
disp( 'In newstats mean' );
in subfunction mean()
>> [ av med ] = newstats( 1:11 )
In newstats mean
av = 6
med = 6
41
Subfunctions
Strange but True
Although you can't access subfunctions
from outside their file, you can get help
on them!
1. Write normal help stuff for subfunction
2. On command line type
help filename>subfunction_name
where filename is the name of the file
(without the .m) that the subfunction is in
42
Subfunctions
Try It
After the function line for my_median put
some help lines and print them by using
the help command on the command line
function m = my_median(v, n)
% This is my median
% Land that I love
>> help newstats>my_median
This is my median
Land that I love
43
Subfunctions
Questions?
44
Nested
Functions
function3
45
Nested Functions
A nested function is a function defined
within another function
Nested functions often passed by
function handle to functions that
manipulate other functions
– e.g., ezplot(), fminbnd(), etc.
– Can be used instead of anonymous functions if
function has more than one expression
46
Nested Functions
To define a nested function, just
write it within another function
Example
function outer( a, b, c )
...
function inner( a )
...
end
...
end
Nested
function
47
Nested Functions
Nested functions
• Can be nested within other nested
functions
• Cannot be inside any MATLAB program
control statement, i.e., if, else,
elseif, switch, for, while,
try, or catch statement
• Must always be terminated by an
end statement
48
Nested Functions
MATLAB Help says:
"M-file functions don't normally require a
terminating end statement. This rule does
not hold, however, when you nest
functions. If an M-file contains one or more
nested functions, you must terminate all
functions (including subfunctions) in the
M-file with end, whether or not they
contain nested functions."
49
Nested Functions
You can call a nested function
• From the level immediately above
it. (In the following code, function
A can call B or D, but not C or E.)
• From a function nested at the
same level within the same parent
function. (Function B can call D,
and D can call B.)
• From a function at any lower level.
(Function C can call B or D, but
not E.)
• You can also call a subfunction
from any nested function in the
same M-file.
function A(x, y) % Primary function
B(x, y);
D(y);
function B(x, y) % Nested in A
C(x);
D(y);
function C(x) % Nested in B
D(x);
end
end
function D(x) % Nested in A
E(x);
function E(x) % Nested in D
...
end
end
end
50
Nested Functions
The scope of a variable is the range
of functions that have direct access
to the variable.
When define a variable in a function,
scope normally that function alone
• Calling function cannot access called
function's variables
• A subfunction cannot access another
subfunction's variables
51
Nested Functions
Big power of nested functions:
A nested function has
access to the variables in all
functions in which it is nested
52
Nested Functions
• A variable that has a value assigned
to it by the primary function can be
read or overwritten by a function
nested at any level within the
primary
• A variable that is assigned in a
nested function can be read or
overwritten by any of the functions
containing that function
53
Example – download
Nested Functions
and run nested_fibonacci.m
function nested_fibonacci % primary function
% nested function
function sum = print_and_sum( ix )
if ix < 3
sum = 1;
else
% nested function can access "indexes"
% variable in containing function
sum = indexes(ix-1) + indexes(ix-2);
fprintf( '%d = %d + %d\n', sum,...
indexes(ix-1), indexes(ix-2) );
end
end
indexes = 1:8;
% apply print_and_sum to every element of numbers,
% save results in a vector and display the vector
fib = arrayfun( @print_and_sum, indexes );
fib
end % end of nested_fibonacci
54
Nested Functions
Questions?
55
The End
56