1 >> Lecture 3
2 >>
3 >> -- Functions
4 >>
Zheng-Liang Lu 165 / 204
Functions
A functionis a piece of computer code that accepts aninput argument from the user and providesoutput to the program.
Functions allow you tomodularizea program by separating its tasks into self-containedunits.
We can program more efficientlyandavoid rewriting the computer code for calculations that are performed frequently.
There are plenty of built-in functions provided by MATLAB.
Note that most of them can be implemented by yourself.
Write down the algorithm first, and then program it.
Zheng-Liang Lu 166 / 204
Built-in Arithmetic Functions
Zheng-Liang Lu 167 / 204
Built-in Rounding Functions
Zheng-Liang Lu 168 / 204
Built-in Discrete Math Functions
Zheng-Liang Lu 169 / 204
Built-in Max Functions
Zheng-Liang Lu 170 / 204
Built-in Max Functions (Cont’d)
There are also min functions to find the minimal elements in arrays, similar to max.
Zheng-Liang Lu 171 / 204
Built-in Average Functions
Zheng-Liang Lu 172 / 204
Built-in Size Functions
Zheng-Liang Lu 173 / 204
Variance and Standard Deviation
Zheng-Liang Lu 174 / 204
Random Number Generators
rand is used to produce a test data for your program.
rand is also widely used in Monte Carlo simulation and random number generation algorithms of other distributions.1
1See computational statistics.
Zheng-Liang Lu 175 / 204
User-Defined Functions
The syntax of a user-defined function is given by
1 function [output var]=function name(input var)
2 % comment section
The output variables, if there exist, are enclosed in square brackets.
The input variables, if there exist, must be enclosed with parentheses.
function name should start with a letter, and be thesameas the file name in which it is saved.
Before this function can be used, it must be saved into the current folder2.
2If not, change the current folder or add the path.
Zheng-Liang Lu 176 / 204
Functions without Input and Output
1 function []=star( ) % [] and () can be dropped.
2 theta=pi/2:0.8*pi:4.8*pi;
3 r=ones(1,6);
4 polar(theta,r) % plot in polar coordinate
0.2 0.4
0.6 0.8 1
30
210
60
240 90
270 120
300 150
330
180 0
Zheng-Liang Lu 177 / 204
Example: Addition of Two Numbers
1 function z=myAdd(x,y)
2 % input: x,y (two numbers)
3 % output: z (sum of x and y)
4 z=x+y;
Zheng-Liang Lu 178 / 204
Example: Mean of A Sequence
1 function y=myMean(x)
2 % input: x (array)
3 % output: y (mean)
4
5 sum=0;
6 for i=1:length(x)
7 sum=myAdd(sum,x(i)); % call myAdd
8 end
9 y=sum/length(x);
Zheng-Liang Lu 179 / 204
Numbers of Arguments
nargin determines the number of input arguments in a function when executed.
nargout determines the number of output arguments from a function when executed.
varargin is a special word with two roles:
varargin declares a function withany numberof arguments.3 The variable varargin itself is acell arraycontaining the optional arguments to the function.
varargout is a special word similar to varargin but for outputs.
3Note that varargin must be declared as the last input argument and collects all the inputs from that point onwards.
Zheng-Liang Lu 180 / 204
Example
Extend myAdd to variable-input-length myAdd.
1 function z = myAdd(varargin)
2 switch nargin
3 case 0
4 disp('No input.')
5 case 1
6 x = varargin{1};
7 z = x;
8 case 2
9 x = varargin{1};
10 y = varargin{2};
11 z = x + y;
12 case 3
13 x = varargin{1};
14 y = varargin{2};
15 w = varargin{3};
16 z = x + y + w;
Zheng-Liang Lu 181 / 204
17 otherwise
18 error('\nToo many inputs.\n');
19 end
20 end
nargin, nargout, varargin and varargout provide a flexible design for user-defined functions.
Note that the key word varargin and varargout should be the last item in the list.
This mechanism is so-called function overloading.
Zheng-Liang Lu 182 / 204
Scope of Variables
The variables used in function m files are known as local variables.
Any variable defined within the function exists only for the function to use.
The only way a function can communicatebetween other functions is through input arguments and the outputs it returns.
Unlike local variables,global variables are available to all parts of a computer program.
Useglobalx to declare x as a global variable.
In general, it is a bad idea to define global variables.4
4Recall the modularity.
Zheng-Liang Lu 183 / 204
Example: Local Variables
1 function test
2 x=0;
3 fprintf('%d\n',x);
4 loop(x,5);
5 fprintf('%d\n',x);
6 end
7
8 function loop(x,n)
9 for i=1:n
10 x=x+1;
11 fprintf('%d\n',x);
12 end
13 end
What are the numbers shown?
How to returnx in loop to test?
Zheng-Liang Lu 184 / 204
Example: Global Variable
1 function test1(x)
2 global g
3 g=g+x;
4 disp(g)
5 test2(g)
6 end
7
8 function test2(y)
9 global g
10 g=g+y;
11 disp(g)
12 end
Zheng-Liang Lu 185 / 204
1 clear all
2 clc
3 % main
4 global g
5 g=0;
6 disp(g)
7 test1(1);
1 >>
2 0
3
4 1
5
6 2
What if you take globalout of the function?
Zheng-Liang Lu 186 / 204
Types of User-Defined Functions
Primary functions andsubfunctions Anonymous functions
Nested functions Private functions
Zheng-Liang Lu 187 / 204
Primary Functions and Subfunctions
A function m-file may containmore than one user-defined function.
The first defined function in the file is called the primary function, whose name is the same as the m-file name. All other functions in the file are called subfunctions.
Subfunctions are normally visible onlyto the primary function and other subfunctions in the same file.
Note that the order of the subfunctions does not matter, but function names must beunique within the m-file.
Zheng-Liang Lu 188 / 204
Example
1 function [a c] = circle(r) % primary function
2 a = area(r);
3 c = circumference(r);
4 end
5
6 function y=area(x) % subfunction 1
7 y = pi*x.ˆ2;
8 end
9
10 function v=circumference(u) % subfunction 2
11 v = 2*pi*u;
12 end
Zheng-Liang Lu 189 / 204
1 >> [a c] = circle(2)
2
3 a =
4
5 12.5664
6 7
8 c =
9
10 12.5664
Note that if only one variable is assigned as output of the function, say, circle, then the area is returned while the circumference is dropped.
Zheng-Liang Lu 190 / 204
Example
5One subfunction can be called by other subfunctions in addition to the primary function.
1 function test1
2 fprintf('Hi, there. This is test1.\n');
3 test2;
4 end
5
6 function test2
7 fprintf('Hi, there. This is test2.\n');
8 test1;
9 end
Notice that two subfunctions calling each other can lead to a loop, resulting a fatal crash.
5Thanks to a lively class discussion (MATLAB-238) on June 14, 2014.
Zheng-Liang Lu 191 / 204
Anonymous Functions
Anonymous functions enable you to create a simple function without needing to create an m-file for it.
Anonymous functions are defined by thefunction handle, denoted by @, in the command window or in an m-file, and are available only until the workspace is cleared.
For example,
1 >> f=@(x) x.ˆ2+x+1 % x.ˆ2 allows vectorization.
2 >> f([1 10])
3
4 ans =
5
6 3 111
Zheng-Liang Lu 192 / 204
You can passthe handle of an anonymous function to other functions. (Try.)
You can create anonymous functions having more thanone input.
One anonymous function can call another to implement function composition.
1 >> f = @(x,y) sqrt(x.ˆ2+y.ˆ2); % f is a function ...
handle
2 >> g = @(x,y) f(x,y).ˆ2; % g is a composite function
3 >> g(3,4)
4
5 ans =
6
7 25
Zheng-Liang Lu 193 / 204
Nested Functions
Functions are said to benestedif the functions are defined within the parent function.
A nested function can access the variables of its parent function.
1 function f = parabola(a,b,c)
2 f = @p; %f is a function handle of p
3 function y = p(x) % p shares a, b, and c
4 y = a*x.ˆ2 + b*x + c;
5 end
6 end
Zheng-Liang Lu 194 / 204
1 >> y = parabola(1, 2, 1); % that is y=xˆ2+2*x+1
2 >> y(5)
3
4 ans =
5
6 36
Note that the function parabolareturns a function.
Also, the nested functions are defined anywherewithin the main function. (Why?)
Zheng-Liang Lu 195 / 204
Exercise
67: Without Nested Functions?
1 function y = p(a, b, c)
2 y = @(x) a * x .ˆ 2 + b * x + c;
3 end
6Thanks to a lively class discussion (MATLAB-244) on August 22, 2014.
7Contribution by Ms. Queenie Chang (MAT25108) on March 18, 2015.
Zheng-Liang Lu 196 / 204
Private Functions
Private functions are useful when you want to limit the scope of a function.
A private functions resides in subfolder with the special name private.
The private function is visible onlyto functions in the parent directory.
Note that youcannot call the private function from the command line or from functions outside the parent of the private folder.
Zheng-Liang Lu 197 / 204
Precedence When Calling Functions
We can conduct the following experiment for this:
1 clear; clc;
2 % main
3 n = 10;
4 x = rand(1, n);
5 mu = mean(x);
6 sigma = std(x, mu);
1 function y = mean(x)
2 fprintf('This is my mean.\n');
3 y = sum(x) / length(x)
4 std(x,y); % invoking std function
5 function z = std(x,y)
Zheng-Liang Lu 198 / 204
6 fprintf('This is my 1st std (nested ...
function).\n');
7 z = sqrt(sum(x .ˆ 2) / length(x) - y ˆ 2)
8 end
9 end
10
11 function z = std(x, y)
12 fprintf('This is my 2nd std (subfunction).\n');
13 z = sqrt(sum(x .ˆ 2) / length(x) - y ˆ 2)
14 end
1 function z = std(x, y)
2 fprintf('This is my 3rd std (local file).\n');
3 z = sqrt(sum(x .ˆ 2) / length(x) - y ˆ 2)
4 end
Zheng-Liang Lu 199 / 204
1 function z = std(x,y)
2 fprintf('This is my 4th std (private).\n');
3 z = sqrt(sum(x .ˆ 2) / length(x) - y ˆ 2)
4 end
Zheng-Liang Lu 200 / 204
Precedence When Calling Functions (Concluded)
1 Nested functions
2 Subfunctions within the same file
3 Private functions
4 Local functions in the same directory
5 Built-in functions
6 Standard m files in PATH
Zheng-Liang Lu 201 / 204
Calling Functions
There are four common ways to invoke a function.
As a character string identifying the appropriate function m-file.
1 function y = fun1(x)
2 y = x .ˆ2 - 4; % vectorized function
3 end
1 >> fun1([1 2 3])
2
3 ans =
4
5 -3 0 5
As a function handle to an existing function M-file.
Zheng-Liang Lu 202 / 204
1 >> feval(@fun1, 3) % returns the function value ...
at 3
2
3 ans =
4
5 5
As a string expression.
1 >> fun2 = 'x .ˆ 2 - 4';
2 >> x = fzero(fun2, [0, 3]); % find the root of ...
fun1 in [0,3]
3
4 x =
5
6 2
Zheng-Liang Lu 203 / 204
As an inline function object.
1 >> fun inline = inline(fun2);
2 >> x = fzero(fun inline, [0, 3])
3
4 x =
5
6 2
The function handle method (method 2) is the fastest method, followed by method 1.
In addition to speed improvement, another advantage of using a function handle is thatit provides access to subfunctions, which are normally not visible outside of their m-file.
Zheng-Liang Lu 204 / 204