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:
- Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace.
- Functions, which can accept input arguments and return output arguments. Internal variables are local to the function.
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 statements
- switch statements
- for loops
- while loops
- break statements
if
isequal
,
isempty
, all
and any
. Exercise: Use
help
to find out more about these functions.
switch
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
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.
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
.
magicrank.m
that
contains these MATLAB commands:
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.
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:
-
Write a short function which converts from samples to milliseconds, given
the number of samples
numSamples
and the sampling frequencyfs
.
eg
>> samptomilli(500,16000)
In other words, 500 samples at a sampling frequency of 16 kHz is equivalent to 31.25 ms.
ans =
31.2500
-
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)
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.
ans =
700
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.
Experienced MATLAB users like to say "Life is too short to spend writing for loops."
A vectorised version of the same code is
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