UCL Department of Phonetics and Linguistics

Introduction to Computer Programming with MATLAB

Lecture 2: Programming Environment

Objectives

 

By the end of the session you should:

q       create and execute simple programs in MATLAB

q       understand the difference between constants, variables and expressions

q       know how to use the assignment statement

q       know how to perform simple manipulations of 1-dimensional arrays (vectors)

Outline

 

1.      MATLAB Windows

 

The MATLAB Command Window is the main window where you type commands directly to the MATLAB interpreter.  The MATLAB Editor Window is a simple text editor where you can load, edit and save complete MATLAB programs.  The Editor window also has a menu command (Debug/Run) which allows you to submit the program to the command window.  The MATLAB Help Window gives you access to a great deal of useful information about the MATLAB language and MATLAB computing environment.  It also has a number of example programs and tutorials.

 

2.      A first program

 

The command

disp(argument);

displays the value of the argument.  This can be a number, a string in single quotes, or an expression.  For simple numbers, the arithmetic operators are: +, -, *, / and ^.  Try

disp(2*3+1);

or

disp(’Hello World!’);

Try these programs out first on the command line; then practise using the editor to enter the commands, saving them to a file, loading the file and running the program from inside the editor.

 

3.      Variables and assignment

 

Variables are named locations in memory where numbers, strings and other elements of data may be stored while the program is working.  Variable names are combinations of letters and digits, but must start with a latter.  MATLAB does not require you to declare the names of variables in advance of their use.  This is actually a common cause of error, since it allows you to refer accidentally to variables that don’t exist.  To assign a variable a value, use the assignment statement.  This takes the form

variable=expression;

for example

a=6;

or

name=’Mark’;

To display the contents of a variable, use

disp(variable);

 

4.      Arrays

 

MATLAB is particularly powerful in the way it deals with tables of data, called arrays.  An array is simply a variable that can contain a number of values arranged in tabular form.  Arrays may be one dimensional (like a list), two dimensional (like a table), or have more dimensions.  To set the value of one element of a one dimensional array, use the notation

variable(index)=expression;

 for example

table(1)=3;

table(2)=6;

Note that indexes must be expressions evaluating to positive integers.  The smallest index is 1.  To access one element from a one dimensional array, use the notation

variable(index)

for example

a=table(2);

disp(table(2));

For two dimensional arrays, use

variable(index,index)=expression;

to set the value and

variable(index,index)

to retrieve its value.  You can store strings in tables, but each string occupies a row, and all rows must be the same length (think of a two-dimensional array of characters). 

 

You can assign a whole array in one operation using a notation involving square brackets: for example:

array = [ v11 v12 v13; v21 v22 v23];

where v11 is the value in row 1 col 1; v21 is the value in row 2 col 1; etc.  The ‘;’ marks the end of a row.

 

You can generate arrays containing sequences very easily with the ‘:’ operator.  The expression

start:stop

generates a sequence of integers from start to stop.  The expression

start:increment:stop

generates a sequence from start to stop with the specfied increment.  Try

disp(1:10);

disp(1:2:10);

 

You can also select sub-parts of the array with the ‘:’ operator.  For example,

x(3:5)

represents the array consisting of the third through fifth elements of x.  Also

y(2:2:100)

represents the array containing the even number elements of y below index 100.

 

You can also add subtract, multiply and divide arrays of data using the operators we’ve mentioned previously.  However MATLAB makes a difference between operations that work on a cell-by-cell basis (so-called “dot” operations) as opposed to operations that work on the arrays as a whole. For example, if you want to multiply two arrays of equal size to give a third array in which each cell contains the product of the corresponding cells in the input, then you need to use the “dot-multiply” operator .* for example

C = A.*B;

 

Finally you can transpose rows and columns of a matrix with the ' operator, for example

disp(A')

 

Reading

"Getting Started: Expressions" 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.  To run the programs, use the Debug/Run menu option or cut and paste the code into the command window.  When you save the files, give them the file extension of ".m".

1.      Write a program (ex21.m) to assign the following expressions to a variable A and then to print out the value of A.

            a)        

            b)        

            c)        

            d)         (0.0000123 + 5.67×10-3) × 0.4567×10-4

2.      Celsius temperatures can be converted to Fahrenheit by multiplying by 9, dividing by 5, and adding 32.  Assign a variable called C the value 37, and implement this formula to assign a variable F the Fahrenheit equivalent of 37 Celsius (ex22.m).

3.      Set up a vector called N with five elements having the values: 1, 2, 3, 4, 5.  Using N, create assignment statements for a vector X which will result in X having these values:

            a)         2, 4, 6, 8, 10

            b)         1/2, 1, 3/2, 2, 5/2

            c)         1, 1/2, 1/3, 1/4, 1/5

            d)         1, 1/4, 1/9, 1/16, 1/25

      (ex23.m)

4.      A supermarket conveyor belt holds an array of groceries.  The price of each product (in pounds) is [ 0.6 1.2 0.5 1.3 ] ; while the numbers of each product are [ 3 2 1 5 ].  Use MATLAB to calculate the total bill (ex24.m).

5.      (Advanced) The sortrows(X) function will sort a vector or matrix X into increasing row order.  Use this function to sort a list of names into alphabetical order. (ex25.m)

6.      (Advanced) The “identity” matrix is a square matrix that has ones on the diagonal and zeros elsewhere. You can generate one with the eye() function in MATLAB. Use MATLAB to find a matrix B, such that when multiplied by matrix A=[ 1 2; -1 0 ] the identity matrix I=[ 1 0; 0 1 ] is generated.  That is A*B=I. (ex26.m)

7.      (Homework) Create an array of N numbers.  Now find a single MATLAB statement that picks out from that array the 1,4,9,16,…,√Nth entries, i.e. those numbers which have indices that are square numbers.