Stuart N WrigleyBSc(Hons) PhD MIET MBCS SMIEEE MAHEP
Operations and Business Development Manager, UKRI CDT in Speech and Language Technologies and their Applications

Session 2: Scripts, functions and control structures

Session 1 | Session 2 | Session 3 | Session 4

To get the full benefit of these matlab introduction sessions, try each example in MATLAB. Also, have you completed Session 1? If not, go back to it first.

Introduction
MATLAB is a powerful programming language as well as an interactive computational environment. Files that contain code in the MATLAB language are called M-files. You create M-files using a text editor, then use them as you would any other MATLAB function or command.

There are two kinds of M-files:

If you duplicate function names, MATLAB executes the one that occurs first in the search path. To view the contents of an M-file, for example, myfunction.m, use

>> type myfunction

Flow control
MATLAB has five flow control constructs:

if

if rem(n,2) ~= 0 M = odd_magic(n) elseif rem(n,4) ~= 0 M = single_even_magic(n) else M = double_even_magic(n) end Note: The above shows comparisons on scalars. Several functions are helpful for reducing the results of matrix comparisons to scalar conditions for use with if, including isequal, isempty, all and any.
Exercise: Use help to find out more about these functions.

switch

switch (rem(n,4)==0) + (rem(n,2)==0) case 0 M = odd_magic(n) case 1 M = single_even_magic(n) case 2 M = double_even_magic(n) otherwise error(’This is impossible’) end Note for C programmers: Unlike the C language switch statement, MATLAB’s switch does not fall through. If the first case statement is true, the other case statements do not execute. So, break statements are not required.

for
Note, this example shows a nested for loop.

for i = 1:m for j = 1:n H(i,j) = 1/(i+j); end end In C, C++ or Java, this for loop would be written as
for(int i=1; i < m+1; i++) { for(int j=1; i < n+1; j++) { H[i][j]=1/(i+j); } } Remember, you can use the colon operator in all the same ways in a for loop declaration as elsewhere. So having for i=60:-5:2 is perfectly valid (syntacticly).

while
The while loop repeats a group of statements an indefinite number of times under control of a logical condition. A matching end delineates the statements.

Here is a complete program, illustrating while, if, else, and end, that uses interval bisection to find a zero of a polynomial.

a = 0; fa = -Inf; b = 3; fb = Inf; while b-a > eps*b x = (a+b)/2; fx = x^3-2*x-5; if sign(fx) == sign(fa) a = x; fa = fx; else b = x; fb = fx; end end x

break
The break statement lets you exit early from a for or while loop. In nested loops, break exits from the innermost loop only.

Scripts
When you invoke a script, MATLAB simply executes the commands found in the file. Scripts can operate on existing data in the workspace, or they can create new data on which to operate. Although scripts do not return output arguments, any variables that they create remain in the workspace, to be used in subsequent computations. In addition, scripts can produce graphical output using functions like plot.

Exercise: Create a file called magicrank.m that contains these MATLAB commands:

% Investigate the rank of magic squares r = zeros(1,32); for n = 3:32 r(n) = rank(magic(n)); end r bar(r)

Don't worry about the use of the for loop - we'll cover that later in this session.
Typing the statement
>> magicrank
causes MATLAB to execute the commands, compute the rank of the first 30 'magic' squares, and plot a bar graph of the result. After execution of the file is complete, the variables n and r remain in the workspace.

Functions
Functions are M-files that can accept input arguments and return output arguments. The name of the M-file and of the function should be the same. Functions operate on variables within their own workspace, separate from the workspace you access at the MATLAB command prompt.

A good example is provided by rank. The M-file rank.m is available in the directory
toolbox/matlab/matfun
You can see the file with
>> type rank
Here is the file.

function r = rank(A,tol) % RANK Matrix rank. % RANK(A) provides an estimate of the number of linearly % independent rows or columns of a matrix A. % RANK(A,tol) is the number of singular values of A % that are larger than tol. % RANK(A) uses the default tol = max(size(A)) * norm(A) * eps. s = svd(A); if nargin==1 tol = max(size(A)) * max(s) * eps; end r = sum(s > tol);

The first line of a function M-file starts with the keyword function. It gives the function name and order of arguments. In this case, there are up to two input arguments and one output argument.

The next several lines, up to the first blank or executable line, are comment lines that provide the help text. These lines are printed when you type
>> help rank
The first line of the help text is the H1 line, which MATLAB displays when you use the lookfor command or request help on a directory.

The rest of the file is the executable MATLAB code defining the function. The variable s introduced in the body of the function, as well as the variables on the first line, r, A and tol, are all local to the function; they are separate from any variables in the MATLAB workspace.

This example illustrates one aspect of MATLAB functions that is not ordinarily found in other programming languages - a variable number of arguments. The rank function can be used in several different ways:
>> rank(A)
>> r = rank(A)
>> r = rank(A,1.e-6)
Many M-files work this way. If no output argument is supplied, the result is stored in ans. If the second input argument is not supplied, the function computes a default value. Within the body of the function, two quantities named nargin and nargout are available which tell you the number of input and output arguments involved in each particular use of the function. The rank function uses nargin, but does not need to use nargout.

Exercise:

  1. Write a short function which converts from samples to milliseconds, given the number of samples numSamples and the sampling frequency fs.
    eg
    >> samptomilli(500,16000)
    ans =
    31.2500
    In other words, 500 samples at a sampling frequency of 16 kHz is equivalent to 31.25 ms.
  2. Once you have done this, try making the frequency variable fs optional. ie, if it isn't supplied, use a default value (say 1000 Hz).
    eg
    >> samptomilli(700)
    ans =
    700
    Note, the use of optional arguments in this example is a little contrived as you would always want to supply the sampling frequency. However, the practice is useful.

Vectorisation
To obtain the most speed out of MATLAB, it’s important to vectorise the algorithms in your M-files. Where other programming languages might use for or do loops, MATLAB can use vector or matrix operations. A simple example involves creating a table of logarithms.

x = 0; for k = 1:1001 y(k) = log10(x); x = x + .01; end

Experienced MATLAB users like to say "Life is too short to spend writing for loops." A vectorised version of the same code is

x = 0:.01:10; y = log10(x); For more complicated code, vectorisation options are not always so obvious. When speed is important, however, you should always look for ways to vectorise your algorithms.

Exercise: In one (short) line, calulate the sum of the cubes of all integers from 5 to 20.

Session 1 | Session 2 | Session 3 | Session 4