Functions
Tan Do
Vietnamese-German University
Lecture 4
Tan Do (VGU) Programming for engineers Lecture 4 1 / 30
Content
In this lecture
Built-in functions.
User-dened functions, function m-les.
Variable scope.
Function handle, anonymous function, primary function, subfunction
and nested function.
Minimizing/maximizing functions.
Tan Do (VGU) Programming for engineers Lecture 4 2 / 30
Built-in functions
Elementary mathematical functions
MATLAB provides many built-in functions including exponential, logarithmic, trigonometric functions, etc. as well
as functions for processing arrays.
Exponential
exp(x) exponential ex
√
sqrt(x) square root x
Logarithmic
log(x) natural logarithm (log base e) ln(x)
log10(x) common logarithm (log base 10) log10 (x)
Complex
abs(x) absolute value of x
angle(x) angle of the complex number x within the range [−π, π]
conj(x) complex conjugate of x
imag(x) imaginary part of the complex number x
real(x) real part of the complex number x
Numeric
ceil(x) round to the nearest integer toward +∞
floor(x) round to the nearest integer toward −∞
fix(x) round to the nearest integer toward 0
round(x) round toward the nearest integer
if
+1
x > 0,
sign(x) signum function: sign(x) = 0 if x = 0,
if
−1 x < 0.
Tan Do (VGU) Programming for engineers Lecture 4 3 / 30
Built-in functions
Trigonometric functions
Trigonometric
sin(x) sine function
cos(x) cosine function
tan(x) tangent function
cot(x) cotangent function
Inverse trigonometric
asin(x) inverse sine
acos(x) inverse cosine
atan(x) inverse tangent
acot(x) inverse cotangent
Note the following 2 points.
The arguments for the trigonometric functions above must be in radian. For trigonometric
functions operating in degree mode, we append the letter d to the functions name. For
example, sind(90) gives 1 in MATLAB.
The inverse trig functions above return values in radian.
Tan Do (VGU) Programming for engineers Lecture 4 4 / 30
Built-in functions
Vectorized functions
The MATLAB built-in functions automatically operate on array arguments to produce
an array result with the same size as the array arguments.
These functions are called vectorized functions.
» v = [0:0.5:3];
» sqrt(v) % The square root function operates on each element of the vector v
ans =
0 0.7071 1.0000 1.2247 1.4142 1.5811 1.7321
When multiplying or dividing functions, or when raising the functions to a power, we
must use element-by-element operations if the arguments are arrays.
For example, to compute z = ey sin x
cos2 x
, we must type
» z = exp(y).* sin(x) ./ (cos(x)).b2
Tan Do (VGU) Programming for engineers Lecture 4 5 / 30
User-dened functions
Function le
Recall that we dened a type of m-le called script le before.
Here we introduce another type of m-le called function le.
To create a function le, open MATLAB editor.
The rst line in a function le must begin with a function denition line which has a list
of inputs and outputs. This line distinguishes a function m-le from a script m-le.
The syntax is
function [output variables] = function_name(input variables)
The output variables are the ones computed by the function using the values of the
input variables.
The output variables must be enclosed by square brackets and the input variables must
be enclosed by parentheses.
If there is only one output variable, the square brackets are optional.
Tan Do (VGU) Programming for engineers Lecture 4 6 / 30
User-dened functions
Some simple rules when dealing with a function le:
We save a function le under the same name as its
function_name.
Function names follow the same rules as naming variables, i.e., they
start with a letter and can contain letters, digits or underscores.
Before naming a function, it is helpful to use the exist function to
see if another function has the same name.
exist(’name’) returns 0 if the name name does not exist, 1 if
name is a variable name in the Workspace and 5 if name is a built-in
function, etc.
Tan Do (VGU) Programming for engineers Lecture 4 7 / 30
User-dened functions
Examples
Suppose we want to dene the function
p 5 ln y
f (x, y) = x2 + y 2 + .
(x2 + 1)5
In MATLAB editor, type
function z = fun(x,y)
a = sqrt(x.b2 + y.b2);
b = 5*log(y) ./ (x.b2 + 1).b5;
z = a + b;
Save the function le under the same name as the function name, i.e., fun.m (note the
extension is .m).
To call the function, at the command line, type
» fun(1,1)
ans =
1.4142
Tan Do (VGU) Programming for engineers Lecture 4 8 / 30
User-dened functions
Next we want to write a function to compute the area and the circumference of a circle with a
given radius.
function [A,C] = circle(r)
% Compute area and circumference of a circle with a given radius.
A = pi*r.b2;
C = 2*pi*r;
At the command prompt, type
» [A,C] = circle(5)
A =
78.5398
C =
31.4159
Note that our function circle can operate on array.
» [A,C] = circle(1:6)
A =
3.1416 12.5664 28.2743 50.2655 78.5398 113.0973
C =
6.2832 12.5664 18.8496 25.1327 31.4159 37.6991
Tan Do (VGU) Programming for engineers Lecture 4 9 / 30
User-dened functions
Comment lines
The line in the circle function le
% Compute area and circumference of a circle with a given
radius.
is called the comment line.
Note the following.
Comment lines always start with % sign.
Comment lines can be placed anywhere in a function le.
If you use help function to obtain information about a function, MATLAB
displays all comment lines immediately following the function denition line, up to
the rst blank line or the rst executable line.
The rst comment line can also be accessed by the lookfor function.
Tan Do (VGU) Programming for engineers Lecture 4 10 / 30
Variable scope
Local variables
There is a fundamental dierence between a script le and a function le.
When a script le is called at the command line, its variables will be stored in the base
workspace.
Figure: Variable student is available in base workspace when the script le StudentDatabase is run.
Tan Do (VGU) Programming for engineers Lecture 4 11 / 30
Variable scope
Whereas when a function le is called at the command line, its variables will be stored in
the function workspace. This means that those variables are available within the
function only. We say that all the variables in a function le are local variables.
Figure: Variables in a function le are local.
Note that in the above gure, the variables a, b and c do not appear in the Workspace
window.
Tan Do (VGU) Programming for engineers Lecture 4 12 / 30
Variable scope
Global variables
The global command declares certain variable global. This means that the values of global
variables are available to the base workspace and also to other functions that declare these
variables global.
To declare the variables A, U and W global, the syntax is
global A U W
It is customary (but not required) to capitalize the names of global variables.
Note that in the syntax, variables are separated by spaces, not commas.
If the global variable is not assigned a value, it will be initialized to the empty array.
Figure: Global variable initialized to the empty array.
Tan Do (VGU) Programming for engineers Lecture 4 13 / 30
Variable scope
In a user-dened function, make the global command the rst executable line.
Also place the same command in the calling program.
Figure: Declaring and assigning values to global variables
It is not always clear to declare a certain variable global.
It is recommended to avoid using global variables in MATLAB. This can often be done
by using anonymous and nested functions introduced later.
Tan Do (VGU) Programming for engineers Lecture 4 14 / 30
Function optimization
Function handles
To refer to a given function, we use a function handle.
To create a function handle, we put @ sign before the function name.
For example, consider the following user-dened function which computes
y = x + 2e−x − 3.
The function le is
function y = myfun(x)
y = x + 2*exp(-x) - 3;
Save this function le under the name myfun.m.
The handle of this function is @myfun.
Tan Do (VGU) Programming for engineers Lecture 4 15 / 30
Function optimization
Function functions
Some MATLAB functions act on functions.
These functions are called function functions.
We use the function handle of a function to pass that function to the
calling function.
Application to nding zeros of a function We use the fzero function to
nd zeros of a function of one variable.
Its syntax is
fzero(@function, x0),
where @function is a function handle and x0 is a guess for the zero.
The function fzero then returns a value that is close to x0.
Tan Do (VGU) Programming for engineers Lecture 4 16 / 30
Function optimization
Remember the following regarding fzero function.
fzero only returns a zero where the graph of the function crosses the
x-axis. If the graph only touches the x-axis, no zero will be found.
Example fzero cannot be used to nd the zero of y = x2 .
fzero returns real-valued zero only. If the search fails, fzero
returns NaN.
To nd a zero of a function within an interval, the syntax is
fzero(@function, [x1, x2]).
x1 and x2 are chosen such that
function(x1) ∗ function(x2) < 0
to guarantee the zero exists.
Tan Do (VGU) Programming for engineers Lecture 4 17 / 30
Function optimization
Finding a minimum of a function
The fminbnd function nds the minimum of a function of a single
variable.
Its syntax is
fminbnd(@function, x1, x2)
where @function is a function handle.
The fminbnd function returns a value within the interval [x1 , x2 ].
Example fminbnd(@cos, 0, 4) returns x = 3.1416.
Tan Do (VGU) Programming for engineers Lecture 4 18 / 30
Function optimization
Be careful that fminbnd can give a misleading answer.
Example Suppose we want to minimize the function
y = x3 + 7x2 − 6x + 5
over the interval [−10, 5].
First we create the function.
function y = f(x)
y = x.b3 + 7*x.b2 - 6*x + 5;
To minimize f over [−10, 5], type
» fminbnd(@f,-10,5)
ans =
0.3951
Note that the answer is the local minimum
of f on the interval [−10, 5],
which corresponds to zero slope.
The TRUE (global) minimum of f on
[−10, 5] is at x = −10. Figure: Graph of y = x3 + 7x2 − 6x + 5 over [−10, 5]
So to get the correct answer, it
is very important to species a good interval.
This can be done by plotting the function. (Plotting is discussed in later lecture.)
Tan Do (VGU) Programming for engineers Lecture 4 19 / 30
Function types
Anonymous function
To create a simple function, it is inconvenient to go through the m-le.
Using anonymous functions provides an easy way to create simple functions.
You can construct an anonymous function at the command line or from
within another function le.
The syntax is
fhandle = @(arglist) expr
where arglist is a list of input arguments separated by commas and
expr is the function formula.
Note that this syntax creates a function handle.
Tan Do (VGU) Programming for engineers Lecture 4 20 / 30
Function types
Example
To create y = x3 + 1, type
cubicf = @(x) x.b3 + 1;
Parentheses are used to improve readability.
cubicf = @(x) (x.b3 + 1);
To create function y = x2 + y 2 , type
p
h = @(x,y) sqrt(x.b2 + y.b2);
Tan Do (VGU) Programming for engineers Lecture 4 21 / 30
Function types
Function composition
We can use anonymous function to create a composite function.
For example, to create y = 10 tan(x2 + 1), you can type
u = @(x) (x.b2 + 1);
v = @(x) 10*tan(x);
y = @(x) v(u(x));
To evaluate the function at a particular value, say x = 2, at the command
line type
» y(2)
ans =
-33.8052
Tan Do (VGU) Programming for engineers Lecture 4 22 / 30
Function types
Subfunction
A function m-le may contain more than one user-dened function.
The rst user-dened function is called the primary function.
All other subsequent functions are call subfunctions.
For example, given a list of numbers x1 , x2 , . . . , xn . Suppose we want to
write a function to calculate the average µ and the standard deviation σ of
this list
sP
n
x1 + x2 + . . . + xn − µ)2
i=1 (xi
µ= and σ = .
n n−1
Tan Do (VGU) Programming for engineers Lecture 4 23 / 30
Function types
The function le is as follows.
function [ave,sd] = statsubfun(x) % the primary function
ave = avefun(x);
sd = sdfun(x,ave);
function m = avefun(y) % subfunction
m = sum(y)/length(y);
function s = sdfun(y,m) % subfunction
u = (y - m).b2;
s = sqrt(sum(u)/(length(y)-1));
At the command prompt, try
» x = [80, 75, 91, 60, 79, 89, 65, 80, 95, 50, 81];
» [ave,sd] = statsubfun(x)
ave =
76.8182
sd =
13.6661
Tan Do (VGU) Programming for engineers Lecture 4 24 / 30
Function types
Subfunctions have the following features.
The name of a function le should be the same as the primary
function name.
Subfunctions can be typed in any order in a function le.
Each of the functions in a le can call any of the other functions in
the same le.
Each of the functions in a le has its own function workspace. This
means that the variables are all local. In other words, the primary
function and the subfunctions cannot access each other's variables
(unless a variable is declared global).
Tan Do (VGU) Programming for engineers Lecture 4 25 / 30
Function types
Nested function
A nested function is a user-dened function written inside another
user-dened function.
The code for a nested function starts with the function denition line and
ends with an end statement.
An end statement must also be placed at the end of the function which
contains the nested function.
A nested function can contain another nested function. But having many
nesting levels might cause confusion.
Here we consider only two levels of nested functions.
Tan Do (VGU) Programming for engineers Lecture 4 26 / 30
Function types
One nested function
function y = A(a1,a2) % the primary function
...
function z = B(b1,b2) % nested function
...
end
...
end
Note the end statements at the ends of the functions A and B.
The nested function B can access the workspace of the primary function A and vice versa.
This means that a variable in the primary function A can be read and redened by the
nested function B and vice versa.
Functions A and B can call each other.
Tan Do (VGU) Programming for engineers Lecture 4 27 / 30
Function types
Two nested functions at the same level
function y = A(a1,a2) % the primary function
...
function z = B(b1,b2) % nested function
...
end
function w = C(c1,c2) % nested function
...
end
...
end
The 3 functions A, B and C can access the workspace of each other.
Functions A, B and C can call each other.
Tan Do (VGU) Programming for engineers Lecture 4 28 / 30
Function types
An example
We reconsider the example in page 20.
Given a list of numbers x1 , x2 , . . . , xn . Suppose we want to write a function to calculate the
average µ and the standard deviation σ of this list
sP
n
x1 + x2 + . . . + xn − µ)2
i=1 (xi
µ= and σ= .
n n−1
We will use nested functions to create the function le.
function [ave,sd] = statnestedfun(x) % the primary function
ave = avefun(x);
sd = sdfun(x);
function m = avefun(x) % nested function
m = sum(x)/length(x);
end
function s = sdfun(x) % nested function
u = (x - ave). b2;
s = sqrt(sum(u)/(length(x)-1));
end
end
This code produces the same results as those in Subfunction section.
Tan Do (VGU) Programming for engineers Lecture 4 29 / 30
Function types
Two levels of nested functions
function y = A(a1,a2) % the primary function
...
function z = B(b1,b2) % nested in A
...
function z = C(c1,c2) % nested in B
...
end
end
function w = D(d1,d2) % nested in A
...
function z = E(e1,e2) % nested in D
...
end
end
...
end
A nested function can be called from a level above it. (Here A can call B and D, but not C and E.)
A nested function can be called by another nested level at the same level within the primary function. (Here
B can call D and vice versa.)
A nested function can be called from any lower level.
A variable in the primary function is recognized and can be redened by a function which is nested at any
level within the primary function.
A variable in a nested function is recognized and can be redened by any function which contains that nested
function.
Tan Do (VGU) Programming for engineers Lecture 4 30 / 30