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:
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
exp(1)
ans = 2.7183
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
function outputs = function_name(inputs)
 
commands
 
end
Where

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
Enter the MATLAB code below in the code cell in the Example functions section at the end of this live script (link to code cell)
function y = dbl(x)
 
% This function doubles the value of the input x
y = 2*x;
 
end
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.
% dbl(3)

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
Enter the MATLAB code below in the code cell in the Example functions section at the end of this live script (link to code cell).
function myfunc
 
% This function is a dummy function to demonstrate local variables
a = 2;
fprintf("The value of the local variable a is %1i.\n", a)
end
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.
% myfunc
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).
% fprintf('%1i', a)

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 .
f(6)
ans = 58
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.
my_abs(-2)
ans = 2
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.
odd_or_even(3)
3 is an odd number
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).
primecheck(3217)
ans = logical
1
primecheck(4233)
ans = logical
0
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 .
magnitude([1, 2, 3])
ans = 3.7417

Functions with multiple inputs

Functions can have multiple inputs which are listed after the function name with commas separating each input.
function outputs = function_name(input1, input2, ...)
 
<commands>
 
end
Example 3
Enter the MATLAB code below in the code cell in the Example functions section at the end of this live script (link to code cell).
function y = x_power_n(x, n)
 
% This function calculates x to the power of n.
y = 1;
for i = 1 : n
y = x * y;
end
 
end
Uncomment the code below to test our function.
x_power_n(2, 5)
ans = 32

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).
g(3, 4)
ans = 73
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.
pythagoras(5, 12)
ans = 13
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])
ans = 70
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])
ans = 1×3
4 -5 2
10. Euclid's algorithm for finding the greatest common divisor (gcd) of two numbers is:
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 .
my_gcd(24, 54)
ans = 6

Functions with multiple outputs

Functions can also output multiple values
function [ output1, output2, ... ] = function_name(input1, input2, ...)
 
<commands>
 
end
The outputs of a function can be accessed by listing the values in an array, e.g.,
[ output1, output2, ... ] = function_name(input1, input2, ...)
or by using an array to contain the outputs, e.g.,
outputs = function_name(input1, input2, ...)
Example 4
Enter the MATLAB code below in the code cell in the Example functions section at the end of this live script (link to code cell).
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;
 
if discriminant < 0
% Quadratic has no real roots
fprintf('No real roots')
root1 = 'no roots'
root2 = 'no roots'
elseif discriminant == 0
 
% Quadratic has one real root
root1 = -b / (2 * a);
root2 = root1;
else
% Quadratic has two real roots
root1 = (-b - sqrt(discriminant)) / (2 * a);
root2 = (-b + sqrt(discriminant)) / (2 * a);
end
 
end
Uncomment the code below to test our function on .
[r1, r2] = quadratic(1, -4, 3)
r1 = 1
r2 = 3

Inline functions

Functions can also be defined using an inline definition.
function_name = @(inputs) outputs;
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.
% Define inline function triple
triple = @(x) 3 * x;
 
% Use the function triple to calculate 3 x 4
triple(4)
Enter this into the code cell below and run the live script.
% Define inline function triple
triple = @(x) 3 * x;
 
% Use the function triple to calculate 3 x 4
triple(4)
ans = 12

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)
cylinder(3, 2)
ans = 56.5487
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.
Example 1
Enter the following commands into the code cell below.
function y = dbl(x)
 
% This function doubles the value of the input x
y = 2 * x;
 
end
function y = dbl(x)
 
% This function doubles the value of the input x
y = 2 * x;
 
end
Example 2
Enter the following commands into the code cell below.
function myfunc
 
% This function is a dummy function to demonstrate local variables
a = 2;
fprintf("The value of the local variable a is %1i.\n", a)
end
function myfunc
 
% This function is a dummy function to demonstrate local variables
a = 2;
fprintf("The value of the local variable a is %1i.\n", a)
 
end
Example 3
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.
y = 1;
for i = 1 : n
y = x * y;
end
 
end
function y = x_power_n(x, n)
 
% This function calculates x to the power of n.
y = 1;
for i = 1 : n
y = x * y;
end
 
end
Example 4
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;
 
if discriminant < 0
% Quadratic has no real roots
fprintf('No real roots')
root1 = 'no roots'
root2 = 'no roots'
elseif discriminant == 0
 
% Quadratic has one real root
root1 = -b / (2 * a);
root2 = root1;
else
% Quadratic has two real roots
root1 = (-b - sqrt(discriminant)) / (2 * a);
root2 = (-b + sqrt(discriminant)) / (2 * a);
end
 
end
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;
 
if discriminant < 0
% Quadratic has no real roots
fprintf('No real roots')
root1 = 'no roots'
root2 = 'no roots'
elseif discriminant == 0
 
% Quadratic has one real root
root1 = -b / (2 * a);
root2 = root1;
else
% Quadratic has two real roots
root1 = (-b - sqrt(discriminant)) / (2 * a);
root2 = (-b + sqrt(discriminant)) / (2 * a);
end
 
end

Exercise functions

Define the functions for the exercises in this live script here.
Exercise 1
1. Define a function called f which calculates the value of the function for an input x.
function y = f(x)
 
y = 2 * x ^ 2 - 3 * x + 4;
 
end
2. Define a function called my_abs which calculates the absolute value of the inputted number.
function y = my_abs(x)
 
% This function calculates the absolute value of x
y = x;
if x < 0
y = -x;
end
 
end
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.
function odd_or_even(x)
 
% This function determines whether x is odd or even.
if mod(x, 2) == 0
fprintf('%1i is an even number', x)
else
fprintf('%1i is an odd number', x)
end
 
end
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.
prime = true;
for i = 2 : x - 1
if mod(x, i) == 0
prime = false;
break
end
end
 
end
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.
mag = 0;
for i = 1 : length(a)
mag = mag + a(i) ^ 2;
end
mag = sqrt(mag);
 
end
Exercise 2
6. Define a function called g which calculates the value of the bivariate function for inputs of x and y.
function z = g(x, y)
 
z = x ^ 2 + y ^ 3;
 
end
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.
c = sqrt(a ^ 2 + b ^ 2);
 
end
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 = 0;
for i = 1 : length(A)
AdotB = AdotB + A(i) * B(i);
end
 
end
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)];
 
end
10. Euclid's algorithm for finding the greatest common divisor (gcd) of two numbers is:
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
% Euclid's algorithm.
 
% Swap a and b if a < b
if a < b
temp = a;
a = b;
b = temp;
end
 
% Euclid's algorithm
while mod(a, b) ~= 0
r = mod(a, b);
b = a;
a = r;
end
y = b;
 
end
Exercise 3
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
% its radius and height.
volume = height * pi * radius ^ 2;
surface_area = 2 * pi * radius^2 + 2 * pi * radius * height;
 
end
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).
expx = 0;
n = 0;
term = 1;
while term > 1e-6
term = x ^ n / factorial(n);
expx = expx + term;
n = n + 1;
end
 
end
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.
x0 = 1;
x1 = 2;
iterations = 0;
 
while abs(x0 - x1) > 0.5e-4
x0 = x1;
x1 = 0.5 * (x0 + s / x0);
iterations = iterations + 1;
end
 
end