1 >> Lecture 4
2 >>
3 >> -- Functions
4 >>
Zheng-Liang Lu 181
Motivation
• A large and complicated problem would be conquered by solving its subproblems.
• So the first step is problem decomposition, that is, separating tasks into smaller self-contained units.
• This is also beneficial tocode reuse without copying the codes.
• Note thatbugs propagate across the program when you copy and paste the codes.
Zheng-Liang Lu 182
Function
• A functionis a piece of program code that acceptsinput argumentsfrom the caller, and then returns output arguments to the caller.
• In MATLAB, the syntax of functions is similar to math functions,
y = f (x ), where x is the input and y is the output.
Zheng-Liang Lu 183
User-Defined Functions
• We can define a new function as follows:
1 function [outputVar] = function name(inputVar)
2 % What to do.
3 end
• This function should be saved in a file with the function name!
• Note that the input/output variables can be optional.
Zheng-Liang Lu 184
Example: Addition of Two Numbers
1 function z = myAdd(x, y)
2 % Input: x, y (any two numbers).
3 % Output: z (sum of x and y).
4 z = x + y;
5 end
• It seems bloody trivial.
• The truth is that the plus operator is actually the function plus.1
• Also true for all the operators like +.
1See https://www.mathworks.com/help/matlab/ref/plus.html.
Zheng-Liang Lu 185
Variable-length Input Argument List
2(Optional)
• We can know the number of input arguments for the function executed by nargin.
• varargin is an input variable in a function definition statement that enables the function to accept any number of input arguments.
• It must be declared as the last input argument and collects all the inputs from that point onwards.
• The variable varargout is a special word similar to varargin but for outputs.
2See https://www.mathworks.com/help/matlab/ref/varargin.html.
Zheng-Liang Lu 186
Example
1 function ret = myAdd(varargin)
2
3 switch nargin
4 case 0
5 disp("No input.");
6 case 1
7 ret = varargin{1};
8 case {2, 3}
9 ret = sum([varargin{:}]);
10 otherwise
11 error("Too many inputs.");
12 end
13 14 end
Zheng-Liang Lu 187
Variable Scope
• Variables in a function are known as local variables, existing only for the function.
• These variables are wiped out when the function finishes its task.
• You may trace the data flow in the program by using the debugger.3
• Let’s set somebreakpoints!!!
3See https://www.mathworks.com/help/matlab/matlab_prog/
debugging-process-and-features.html.
Zheng-Liang Lu 188
Example
1 clear; clc;
2
3 x = 0;
4 for i = 1 : 5
5 addOne(x);
6 disp(x); % output ?
7 end
1 function addOne(x)
2 x = x + 1;
3 end
Zheng-Liang Lu 189
Function Handles & Anonymous Functions
• Anonymous functions are used once and not written in the standard form of functions, for example,
1 f = @(x) x .ˆ 2 + 1 % f is a function handle.
• However, they contain only single statement.
• Besides, we use function handles4 to handle functions.
• This is also called lambda expressions.
• You can also assign an existing function to a handle, for example,
1 g = @sin
4You may refer to https://en.wikipedia.org/wiki/Function_pointer.
The truth is that every function name is an alias of the function address!
Zheng-Liang Lu 190
More Examples
5,6,71 function y = parabolicFunGen(a, b, c)
2 y = @(x) a * x .ˆ 2 + b * x + c;
3 end
1 function y = getSlope(f, x0)
2 eps = 1e-9;
3 y = (f(x0 + eps) - f(x0)) / eps;
4 end
1 function y = differentiate(f)
2 eps = 1e-9;
3 y = @(x) (f(x + eps) - f(x)) / eps;
4 end
5Thanks to a lively class discussion (MATLAB244) on August 22, 2014.
6Contribution by Ms. Queenie Chang (MAT25108) on March 18, 2015.
7Thanks to a lively class discussion (MATLAB260) on September 16, 2015.
Zheng-Liang Lu 191
Vectorization (Revisited)
• We can apply a function to each element of array by arrayfun.8
1 B = arrayfun(@(x) 2 * x, A) % Equivalent to 2 * A.
• cellfun is similar to arrayfun but applied to cells.9
1 >> data = {"NTU", "CSIE", [], "MATLAB"};
2 >> isempty(data) % Output 0.
3 >> cellfun(@isempty, data) % Output 0 0 1 0.
8See https://www.mathworks.com/help/matlab/ref/arrayfun.html.
9See https://www.mathworks.com/help/matlab/ref/cellfun.html.
Zheng-Liang Lu 192
Error and Error Handling
• You can issue/throw an error if you do not allowthe callee for some situations.
1 if bad condition
2 error("So wrong."); % Interrupt the normal flow.
3 end
• As an app programmer, you should use atry-catchstatement to handle errors.
1 try
2 % Normal operations.
3 catch
4 % Handler operations.
5 end
Zheng-Liang Lu 193
Example: Combinations
• For all nonnegative integers n ≥ k, nk is given by
n k
= n!
k!(n − k)!.
• Note that factorial(n) returns n!.
1 clear; clc;
2
3 n = input("n = ? ");
4 k = input("k = ? ");
5 y = factorial(n) / (factorial(k) * factorial(n - k))
6 disp('End of program.');
Zheng-Liang Lu 194
• Try n = 2, k = 5.
• However, factorial(−3) is not allowed!
• The program is not designed to handle this error, so it is interrupted in Line 5 and does not reach the end of program.
• Add error handling to the program:
1 clear; clc;
2
3 n = input("n = ? ");
4 k = input("k = ? ");
5 try
6 y = factorial(n) / (factorial(k) * ...
factorial(n - k))
7 catch e % capture the thrown exception
8 disp("Error: " + e.message); % show the message
9 end
10 disp("End of program.");
Zheng-Liang Lu 195
1 >> Lecture 5
2 >>
3 >> -- Special Topic: Text Processing
4 >>
Zheng-Liang Lu 196
(Most) Common Codec: ASCII
11• Everything in the computer is encoded in binary.
• ASCII is a character-encoding scheme originally based on the English alphabet that encodes 128 specified characters into the 7-bit binary integers (see the next page).
• Unicode10 became a standard for the modern systems from 2007.
• Unicode is backward compatible with ASCII because ASCII is a subset of Unicode.
10SeeUnicode 8.0 Character Code Charts.
11Codec: coder-decoder; ASCII: American Standard Code for Information Interchange, also see http://zh.wikipedia.org/wiki/ASCII.
Zheng-Liang Lu 197
Zheng-Liang Lu 198
Characters and Strings (Revisited)
• Before R2017a, a text is a sequence of characters, just like numeric arrays.
• For example, ’ntu’.
• Most built-in functions can be applied to string arrays.
1 clear; clc;
2
3 s1 = 'ntu'; s2 = 'csie';
4 s = {s1, s2};
5 upper(s) % output: {'NTU', 'CSIE'}
Zheng-Liang Lu 199
• Since R2017a, you can create a string by enclosing a piece of text in double quotes.12
• For example, ”ntu”.
• You can find a big difference between characters and strings in this example:
1 clear; clc;
2
3 s1 = 'ntu'; s2 = 'NTU';
4 s1 + s2 % output: 188 200 202
5
6 s3 = string(s1); s4 = string(s2);
7 s3 + s4 % output: "ntuNTU"
12See https://www.mathworks.com/help/matlab/ref/string.html.
Zheng-Liang Lu 200
Selected Text Operations
13sprintf Format data into string.
strcat Concatenate strings horizontally.
contains Determine if pattern is in string.
count Count occurrences of pattern in string.
endsWith Determine if string ends with pattern.
startsWith Determine if string starts with pattern.
strfind Find one string within another.
replace Find and replace substrings in string array.
split Split strings in string array.
strjoin Join text in array.
lower Convert string to lowercase.
upper Convert string to uppercase.
reverse Reverse order of characters in string.
13See https:
//www.mathworks.com/help/matlab/characters-and-strings.html.
Zheng-Liang Lu 201