MATLAB Functions Part II - Miami University · 2013-10-28 · MATLAB Functions – Part II Greg...
Transcript of MATLAB Functions Part II - Miami University · 2013-10-28 · MATLAB Functions – Part II Greg...
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
3
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
4
Part II
• Document functions
• Detect number of inputs and outputs
• Subfunctions
• Nested functions
Documentation
5
Documentation
6
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
Documentation
7
Look at results for MATLAB csvread()
Try It
1. Type help csvread
2. Type lookfor 'comma separated'
3. Type type csvread
Documentation
8
>> 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.
Documentation
9
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
Documentation
10
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
Documentation
11
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
Documentation
12
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.
Documentation
13
Suggestions for documentation
• H1 line
• Longer description of functionality
• Description of parameters
• Description of errors and how they're
handled
• References
Documentation
14
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
Documentation
15
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
Documentation
16
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
Documentation
17
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
Documentation
18
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.
Documentation
19
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()
Documentation
20
References
• Full citations for books, papers, etc.
• Web sites
– URL
– Date downloaded
• External codes used
– MATLAB central
– sourceforge.net
– university
21
Documentation
Questions?
Input / Output
Arguments
22
Arguments
23
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(...)
Arguments
24
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
Arguments
25
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)
Arguments
26
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
b = 0;
elseif nargin ~= 3
error( 'USAGE: y = scale( x, m, b ) m, b optional' );
end
If missing inputs, set them
If not max number of inputs, bail out
Arguments
27
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
Arguments
28
Can verify range
%verify range
if m == 0
error( 'm must not be zero' );
end
Arguments
29
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
Arguments
30
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
Arguments
31
Example – MATLAB fminbnd() [x,fval] = fminbnd(...) returns the value of the objective function computed in
fun at x.
[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
information about the optimization:
output.algorithm Algorithm used
output.funcCount Number of function evaluations
output.iterations Number of iterations
output.message Exit message
Main results
Exit status
Processing information
Arguments
32
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)
Continues on next slide
Arguments
33
Processing different number of outputs function [ y expansion ] = scale( x, m, b )
% compute main output
if nargout == 1
y = m * x + b;
elseif nargout == 2
y = m * x + b;
expansion = ( max(y) - min(y) ) / ( max(x) - min(x) );
else
error( 'USAGE: [ y expansion ] = scale( x, m, b ) m, b
optional' );
end
If optional output desired,
compute it
If not max number of inputs, bail out
Arguments
34
Try It >> scale( 1:5 )
??? Error using ==> scale at 42
USAGE: [ y expansion ] = scale( x, m, b ) m, b optional
>> 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.
35
Arguments
Questions?
Subfunctions
36
Subfunctions
37
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
Subfunctions
38
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
Subfunctions
39
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
Subfunctions
40
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'.
Subfunctions
41
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
Subfunctions
42
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
Subfunctions
43
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
44
Subfunctions
Questions?
Nested
Functions
45
function3
Nested Functions
46
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
Nested Functions
47
To define a nested function, just
write it within another function
Example
function outer( a, b, c )
...
function inner( a )
...
end
...
end
Nested
function
Nested Functions
48
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
49
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."
Nested Functions
50
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
Nested Functions
51
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
Nested Functions
52
Big power of nested functions:
A nested function has
access to the variables in all
functions in which it is nested
Nested Functions
53
• 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
Nested Functions
54
Example – download 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
55
Nested Functions
Questions?
56
The End