UCL Department of Phonetics and Linguistics

Introduction to Computer Programming with MATLAB

Lecture 4: Procedures and Functions

Objectives

 

By the end of the session you should:

q       know how to create a function that takes arguments

q       understand about argument copying and variable scope

q       know how to give a function a title and a help text

q       know how to request input from the user and to format responses

q       know how to manipulate strings of characters

Outline

 

1. Functions

 

You can define your own functions to complement those provided by MATLAB.  Functions are the building blocks of your own programs.  You should always try and divide your programming task into separate functions, then design, code and test each one independently.  It is common to design from the top down, but build from the bottom up.

 

It is good practice to store each function in its own source file, with the name of the source file matching the function.  Thus a function called “myfunc” will be stored in the file “myfunc.m”.  This way, both you and MATLAB can easily find the source file for a function given its name.  The first line of a function source file should then be the function definition line, which has the format:

function outargs=funcname(inargs);

The function name can be a mixture of letters and digits but must start with a letter.  It is a good idea to avoid names that MATLAB is already using.  The inargs parameter is a list of variable names separated by commas.  These are the dummy names you will use in the code for the function to ‘stand for’ the actual arguments passed to the function when it is executed.  Likewise the outargs parameter is a list of variable names separated by commas which stand for the values returned by the function to the calling program.  Note that a function can take zero or more input arguments and return zero or more values.  Here are some example function definitions:

function y=square(x);

function av=average(x1,x2,x3,x4,x5);

function printvalue(A);

function B=readvalue();

function [mean,sttdev]=analyse(tab);

Following the function line you should write a one line comment that summarises what the function does.  For example:

% square(x) returns the square of the argument x

This line is printed out if the user types

lookfor funcname;

in the command window.  All the comment lines between the function definition and the first executable statement are printed out when the user types

help funcname;

in the command window.  Use this facility to provide some help information to the users of your function.

 

The body of your function will normally perform some computation based on the input arguments and end by assigning some values to the output arguments.  When the function is called from another program, whatever values are supplied to the function are copied into the dummy input arguments, then the function is executed, then the values of the output dummy arguments are inserted into the calculation in the calling program.  It is good practice to end each function with the return statement to remind you that execution returns to the calling program at this point.

 

function y=cube(x)

% cube(x) returns the cube of x

y = x * x * x;

return;

 

a=10;

b=cube(a);

disp(b);              % \

disp(cube(a));        %  All display 1000

disp(cube(10));       % /

 

It is good practice to pass all the information you need for a function through the list of input arguments and to receive all the processed results through the output arguments.  Although this requires a lot of copying, MATLAB does this quite efficiently.  Sometimes however, you may have a number of functions that all require access to the same table of data, and you don’t want to keep copying the table into the function and then copying the changes back into your program.  Imagine if the table had a million elements!  Under these circumstances you can declare variables as ‘global’.  This means that they can be accessed both inside your program and inside a function without having to pass the variable as a function argument.  Here is an example:

 

function initialisetable(num)

% initialise global variable TAB to all the same value

global TAB;

TAB=num*ones(size(TAB));

 

% main program

global TAB;

TAB=zeros(1,100);

initialisetable(5);

 

You can also write functions which take a variable number of arguments.  In fact MATLAB allows any function to be called with fewer arguments than the definition, so it is a good idea to always check the number of arguments supplied.  The built in variable ‘nargin’ contains the number of input arguments actually supplied, and ‘nargout’ contains the number of output arguments.  You can use the built in function ‘error()’ to report an error if the number of arguments is incorrect.  For example:

function m=average(x,y)

if (nargin!=2)

error(’two arguments needed in average()’);

end

We'll meet the if statement in the next lesson.

 

2. Formatted console input-output

 

You can control the exact way in which values are printed to the screen with the ‘fprintf()’ function (fprintf= “file print formatted”).  This function takes one argument repesenting the formatting instructions, followed by a list of values to be printed.  Embedded within the format string are ‘percent commands’ which control where and how the values are to be written.  Here are some examples:

fprintf('The answer is %g seconds.\n',nsec);

fprintf('Day of the week = %s\n',dayofweek([7 12 1941]));

fprintf('Mean=%.3f ± %.4f\n',mean,stddev);

The command %g represents a general real number, %f means a fixed point number, %d a decimal integer, and %s a string.  You can put numeric values between the ‘%’ and the letter to control the field width and the number of digits after the decimal point.  For example (□=space):

 

fprintf('%5g',10)

□□□10

fprintf('%10.4f',123.456)

□□123.4560

fprintf('%10s', 'fred')

□□□□□□fred

 

You can input a value or a string from the command line with the ‘input()’ function.  This has two forms depending on whether you want to input a number or a string:

yval=input('Enter a number: ');

name=input('Enter your name: ', 's');

 

3. String handling

 

Simple strings are stored as tables with one row and a number of columns: one column per character.  You can concatenate any table or strings simply by making the contents part of one table.  For example:

str1='Hello';

str2='Mark ';

str=[str1 ' ' str2];

You can convert numbers to strings using the ‘sprintf()’ function, which operates analogously to the fprintf() function but outputs to a string rather than to the screen.

str=sprintf('%10.4f',123.45);

 

The ‘abs()’ function can be used to find the standard character codes for a string:

disp(abs('Mark'));

    77    97   114   107

The ‘char()’ function can be used to convert character codes back to a string:

disp(char([77 97 114 107]));

Mark

The ‘eval()’ function can be used to evaluate an expression stored in a string.  This allows you to execute expressions typed in by the user:

expr=input('Enter an expression (e.g. "2+3*4") : ', 's');

disp(eval(expr));

 

Reading

"Getting Started: Scripts and Functions" in MATLAB Help.

Exercises

For these exercises, use the editor window to enter your code, and save your answers to files under your account on the central server. When you save the files, give them the file extension of ".m". To run functions, call them by name from the command window.

1.      Write a function called FtoC (ftoc.m) to convert Fahrenheit temperatures into Celsius.  Make sure the program has a title comment and a help page.  Test from the command window with:

            FtoC(96)

            lookfor Fahrenheit

            help FtoC

2.      Write a function (roll2dice.m) to roll 2 dice, returning two individual variables: d1 and d2.  For example:

            [d1 d2] = roll2dice

            d1 =

                  4

            d2=

                  3

3.      Write a function (sinewave.m) to return a sinewave of a given frequency, duration and sample rate.  Replay it to check.  For example:

            s = sinewave(1000,0.5,11025);

            sound(s,11025);

4.      Write a program (ex44.m) to input 2 strings from the user and to print out (i) the concatenation of the two strings with a space between them, (ii) a line of asterisks the same length as the concatenated strings, and (iii) the reversed concatenation.  For example:

            Enter string 1: Mark

            Enter string 2: Huckvale

            Mark Huckvale

            *************

            elavkcuH kraM

5.      (Advanced) Zeller's Congruence is a formula that calculates the day of the week given the date (within a limited range of years).  The formula is:

            day = 1 + ([2.6m - 0.2] + d + y + [y/4] + [c/4] - 2c) modulo 7

where the square brackets mean take the integer part, modulo 7 means the remainder when divided by 7, and

                        d = day of the month (e.g. 1 to 31)

                        m = month number with March=1, ..., December=10, January=11,

                               February=12.  Assign January and February to previous year.

                        c = century number (e.g. 19)

                        y = year in century (e.g. 97), but remember January and February

The result is the day of the week, with 1=Sunday.  Write a function dayofweek (dayofweek.m) which takes a vector of three numbers representing the day, month and year in conventional notation, and returns a string containing the name of the day of the week.  For example (attack on Pearl Harbour):

            dayofweek([7 12 1941])

            ans=

                  Sunday

6.      (Homework) A musical semitone is a frequency interval corresponding to the twelfth root of 2 (i.e. 2^(1/12)). We can number semitones with respect to the 'A' above middle C which has the frequency 440Hz, i.e. semitone 0 = 440Hz, semitone 1 = 466.2Hz, etc.  Write a program which plays the Westminster chimes, with

            tones=[ 0 –4 –2 –9 –9 –2 0 –4 ];