Linear Algebra and Programming Skills
Dr Jon Shiach, Department of Computing and Mathematics, Manchester Metropolitan University
Functions
Learning Outcomes
On successful completion of this page readers will be able to:
- define functions in MATLAB and call them to perform calculations;
- define functions with multiple input and output arguments;
- define simple functions using inline definitions.
A function is a block of code that is used to perform a single action. These are very useful in programming as they allow us to think of a program as a collection of single individual tasks. Functions also allow us to repeat tasks easily without having to write out the individual commands again.
You have already been introduced to functions that come already built-in with MATLAB. For example
Here we have used the exp function to calculate the value of the constant e. Using a function like this is known as calling a function.
Defining functions
Functions in MATLAB are defined using
Where
- function_name is the name which is used to call the function. A function name must begin with a character or underscore and not a number. Also care must be taken not to use the same name as a previously defined function (e.g., if you define a new function called abs then you won't be able to use MATLAB's built-in abs function).
- inputs are variables which are used as inputs to the function.
- outputs are variables which are outputted by the function.
A note about functions in MATLAB Live Scripts
Functions that are defined in MATLAB must be placed at the end of the live script or script file (the exception to this are inline functions which can be used to define simple functions). All functions used in the examples and exercises here are therefore defined in the Example functions and Exercise functions sections at the end of this live script. Example 1
Note that in our dbl function above we have used a comment briefly explain the purpose of the function. This is common practice in programming.
To call our function we use the function name and parse a number into it. Uncomment the command below and run the live script to use our newly defined function.
Local variables
Any variables defined within a function and not outputted command are known as local variables because they can only be accessed from commands within the function. It can be useful to think of a function as a black box in that any variables which are defined within a function cannot be used outside of the function unless they are an output.
Example 2
Here we have defined function myfunc in which we also define a local variable a. The fprintf command is used to show that the local variable a can be accessed in the function. Uncomment the code below and run the live script to call our function.
If we tried to access the value of a outside of the function MATLAB would returns an error (remove the comment symbol in the code cell below to try it).
Exercise 1 - Defining functions
1. Define a function called f in the section at the end of this live script which calculates the value of the function
for an input x (link to code cell). Uncomment the command below to use your function to calculate
. 2. Define a function called my_abs in the section at the end of this live script which calculates the absolute value of the inputted number (link to code cell). Test your function on some values in the code cell below.
3. Define a function called odd_or_even which takes in an input of an integer number and returns the character string 'x is an even number' or 'x is an odd number' depending on the value of the input x (link to code cell). Test your function on some values in the code cell below.
4. Define a function called primecheck that takes in an input of an integer number x and returns True or False depending whether it is an integer or not using a for loop to check whether the numbers between 2 and x-1 are factors of x (link to code cell). Test your function with the numbers 3217 (prime) and 4233 (not prime).
5. Define a function called magnitude that calculates the magnitude of a vector that is inputted into it. Your function should be able to deal with vectors of any length (link to code cell). Test your function on
. Functions with multiple inputs
Functions can have multiple inputs which are listed after the function name with commas separating each input.
Example 3
Uncomment the code below to test our function.
Exercise 2 - Functions with multiple inputs
6. Define a function called g which calculates the value of the bivariate function
for inputs of x and y. Use your function to calculate the value of
(link to code cell). 7. Define a function called pythagoras which takes in two inputs of the lengths of the two shortest sides of a right-angled triangle a and b and returns the length of the hypotenuse c calculated using Pythagoras' theorem (link to code cell).
.Test your function to fine the hypotenuse when the two shortest sides are 5 and 12.
8. Define a function called dot_product that calculates the dot product of two inputted vectors (link to code cell). Test your function on
. dot_product([1, 2, 3, 4], [5, 6, 7, 8])
9. Define a function called cross_product that calculates the cross product of two vectors in
(link to code cell). Test your function on
. cross_product([1, 2, 3], [-1, 0, 2])
10. Euclid's algorithm for finding the greatest common divisor (gcd) of two numbers is:
- Divide the larger number a by the smaller number b and find the remainder
; - Divide b by
and find the remainder
; - Divide
by
and find the remainder
; - Continue in this way until the remainder
then
.
Define a function called my_gcd that uses Euclid's algorithm to calculate the gcd of two numbers (link to code cell). Test your function on
. Functions with multiple outputs
Functions can also output multiple values
The outputs of a function can be accessed by listing the values in an array, e.g.,
or by using an array to contain the outputs, e.g.,
Example 4
Uncomment the code below to test our function on
. [r1, r2] = quadratic(1, -4, 3)
Inline functions
Functions can also be defined using an inline definition.
Unlike the standard method of defining a MATLAB function, inline functions can appear anywhere within a program or live script and are useful for defining simple functions that can be defined using a single line of code.
Example 5
The following commands defines a function called triple and outputs the value of the input multiplied by 3. The function is then used to calculate 3 times 4.
Enter this into the code cell below and run the live script.
% Define inline function triple
% Use the function triple to calculate 3 x 4
Exercise 3 - Functions with multiple outputs
11. Define a function called cylinder that calculates the volume and surface area of a cylinder given inputs of the radius and height. (link to code cell) 12. The series expansion of
is Define a function called my_exp that uses a while loop to compute the value of
by adding the nth term at each iteration. Your while loop should stop when the value of the nth term is less than
. Your function should output the value of
and the number of iterations used to achieve the required accuracy. (link to code cell) Use your function to calculate
which should require 11 iterations. [expx, iterations] = my_exp(1)
expx = 2.7183
iterations = 11
13. A method for calculating the value of
for some real number s uses the iterative scheme Define a function called my_sqrt which uses a while loop to calculate this scheme whilst
where
and
. Your function should output the approximation of
and the number of iterations used. (link to code cell) Test your function on
which should require 4 iterations. [sqrt2, iterations] = my_sqrt(2)
sqrt2 = 1.4142
iterations = 4
Example functions
The example functions used in this live script are defined in this section.
Enter the following commands into the code cell below.
% This function doubles the value of the input x
Enter the following commands into the code cell below.
% This function is a dummy function to demonstrate local variables
fprintf("The value of the local variable a is %1i.\n", a)
Enter the following commands into the code cell below.
function y = x_power_n(x, n)
% This function calculates x to the power of n.
Enter the following commands into the code cell below.
function [root1, root2] = quadratic(a, b, c)
% This function calculates the roots of a quadratic polynomial using
% the quadrative formula.
discriminant = b ^ 2 - 4 * a * c;
% Quadratic has no real roots
% Quadratic has one real root
% Quadratic has two real roots
root1 = (-b - sqrt(discriminant)) / (2 * a);
root2 = (-b + sqrt(discriminant)) / (2 * a);
Exercise functions
Define the functions for the exercises in this live script here.
1. Define a function called f which calculates the value of the function
for an input x. y = 2 * x ^ 2 - 3 * x + 4;
2. Define a function called my_abs which calculates the absolute value of the inputted number. % This function calculates the absolute value of x
3. Define a function called odd_or_even which takes in an input of a integer number and returns the character string 'x is an even number' or 'x is an odd number' depending on the value of the input x. % This function determines whether x is odd or even.
fprintf('%1i is an even number', x)
fprintf('%1i is an odd number', x)
4. Write a function called primecheck that takes in an input of an integer number x and returns True or False depending whether it is an integer or not using a for loop to check whether the numbers between 2 and x-1 are factors of x. function prime = primecheck(x)
% This function checks whether x is prime or not.
5. Define a function called magnitude that calculates the magnitude of a vector that is inputted into it. Your function should be able to deal with vectors of any length. function mag = magnitude(a)
% This function calculates the magnitude of a vector a.
6. Define a function called g which calculates the value of the bivariate function
for inputs of x and y. 7. Define a function called pythagoras which takes in two inputs of the lengths of the two shortest sides of a right-angled triangle a and b and returns the length of the hypotenuse c calculated using Pythagoras' theorem.
.function c = pythagoras(a, b)
% This function calculates the length of the hypotenuse of a right-angled
% triangle using the lengths of the shortest sides a and b.
8. Define a function called dot_product that calculates the dot product of two inputted vectors. function AdotB = dot_product(A, B)
% This function calculates the dot product of two vectors A and B.
AdotB = AdotB + A(i) * B(i);
9. Define a function called cross_product that calculates the cross product of two vectors in
. function AxB = cross_product(A, B)
% This function calculates the cross product of two vectors A and B.
AxB = [A(2) * B(3) - A(3) * B(2), A(3) * B(1) - A(1) * B(3), A(1) * B(2) - A(2) * B(1)];
10. Euclid's algorithm for finding the greatest common divisor (gcd) of two numbers is: - Divide the larger number a by the smaller number b and find the remainder
; - Divide b by
and find the remainder
; - Divide
by
and find the remainder
; - Continue in this way until the remainder
then
.
Define a function called my_gcd that uses Euclid's algorithm to calculate the gcd of two numbers.
function y = my_gcd(a, b)
% This function calculates the greatest common divisor of a and b using
11. Define a function called cylinder that calculates the volume and surface area of a cylinder given inputs of the radius and height. function [volume, surface_area] = cylinder(radius, height)
% This function calculates the volume and surface area of a cyclinder given
volume = height * pi * radius ^ 2;
surface_area = 2 * pi * radius^2 + 2 * pi * radius * height;
12. The series expansion of
is Define a function called my_exp that uses a while loop to compute the value of
by adding the nth term at each iteration. Your while loop should stop when the value of the nth term is less than
. Your function should output the value of
and the number of iterations used to achieve the required accuracy. function [expx, n] = my_exp(x)
% This function calculates the value of exp(x).
term = x ^ n / factorial(n);
13. A method for calculating the value of
for some real number s uses the iterative scheme Define a function called my_sqrt which uses a while loop to calculate this scheme whilst
where
and
. Your function should output the approximation of
and the number of iterations used. function [x1, iterations] = my_sqrt(s)
% This function calculates the square root of s.
while abs(x0 - x1) > 0.5e-4
x1 = 0.5 * (x0 + s / x0);
iterations = iterations + 1;