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 1: Matrix Generation and Manipulation

Session 1 | Session 2 | Session 3 | Session 4

To get the full benefit of these matlab introduction sessions, try each example in MATLAB.

Getting started
When you are in MATLAB, you will see the >> prompt. MATLAB is an interpreted language, and is waiting for you to type in an expression. Think of it as a very sophisticated scientific calculator, if you like.

Try typing some arithmetic expression
>> 98 * 31.4
MATLAB immediately responds with the answer:
ans = 3.0772e+ 03

Now try typing this (MATLAB's response is also shown):
>> power(10,pi/2)
ans = 37.2217

This expression makes use of a MATLAB function - power - and a predefined constant, pi. If you want to see what any MATLAB function does, type help function_name
e. g.
>> help power

Vectors
To represent a vector quantity in MATLAB, write the vector components as a list:
>> v = [1 1 1]; w = [2 3 4];
Note: we have used the semi-colon to separate statements.
Exercise: Repeat the above statement but leave off the last semi-colon. What happens?

Matrices
As the name suggests, MATLAB was designed with matrices in mind. There are many ways to create and manipulate matrices. One way is to create a matrix from the keyboard
>> m = [1 2 3; 4 5 6; 7 8 9]
m =
1 2 3
4 5 6
7 8 9

Note that the semi-colon is used to separate matrix rows.

We can perform various arithmetic operations on matrices (including some which are strictly prohibited by pure matrix algebra!). To add 1 to all elements of m, we write:
>> m + 1
ans =
2 3 4
5 6 7
8 9 10

Matrix operations such as addition, subtraction, scalar and matrix multiplication are all written in the normal way. Here is another matrix:
>> n = [1 0 0; 0 1 0; 0 0 1]
which you'll recognise as the identity matrix.

Now for some matrix operations:
>> m + n
2 2 3
4 6 6
7 8 10
>> m * n
1 2 3
4 5 6
7 8 9

This is what you would expect: multiplication by the identity matrix leaves the matrix unchanged.

MATLAB distinguishes between matrix operations and element- by- element operations, and provides the 'dot' syntax for the latter. The operation
>> m .* n
1 0 0
0 5 0
0 0 9

produces the result of multiplying corresponding elements of the two matrices.

Generating matrices
You can generate the zero matrix of a given size using the zeros command with the number of rows and columns as inputs
>> zeros(2,3)
0 0 0
0 0 0

Similarly, the ones command generates a matrix of ones, rand generates a matrix of uniformly distributed random elements.

An important function is the size command, which returns the dimensions of a matrix:
>> o = ones(3,2); [rows, cols]= size(o);
results in rows having the value 3 and cols the value 2. Note that if you don't want the intermediate matrix o, the two commands could be replaced by the single command:
>> [rows, cols]= size(ones(3,2))

The : operator
This is arguably one of the most important operators in the matlab language. The colon can be used to select subvectors. It is also used to select parts of a matrix. For instance, using the matrix m defined earlier, the command can be used to produce the submatrix of rows 1 and 2 and columns 2 and 3:
>> m(1:2,2:3)
2 3
5 6

The colon on its own selects ALL rows or columns:
>> m(1:2,:)
1 2 3
4 5 6

This is useful when selecting a single row or column of a matrix:
>> m(1,:)
1 2 3

The : operator is also used for generating vectors. For instance, if we wished to generate a vector of the integers 1 to 10:
>> a=1:10
a =
1 2 3 4 5 6 7 8 9 10

This is in fact shorthand for:
>> a=1:1:10
a =
1 2 3 4 5 6 7 8 9 10

ie 'generate a vector starting at 1 and ending at 10 incrementing in steps of 1'.
Exercise: Try

Matrix comparisons
Relational operators such as > and < work with matrices too. To find all elements of m which are less than 6, for example, use:
>> m < 6
1 1 1
1 1 0
0 0 0

The result produces a matrix of the same size as m containing boolean values. These values are the result of the element-by-element operation performed - in this case < 6.

Subscripts
You've already seen how to access part of a matrix using array subscripts. For example
>> m(1:2,:)
1 2 3
4 5 6

If we wanted to obtain all the values of m which are less than 6, we could do:
>> m(m<6)
1
4
2
5
3

Here, we've used logical subscripts: the result of a matrix comparison has been used to reference a number of elements.
Exercise: Try this for different matrix comparisons.
Now, lets try something a little more sophisticated.
Exercise: Using the matrix m produce a second matrix p which is identical to m except for one difference: any values below 6 are set to zero. Note this is the same as the last example except that we don't want to lose the structure. Hint: you will need to use .* Your result should be
0 0 0
0 0 6
7 8 9

Matrix Concatenation
Concatenation is the process of joining small matrices to make bigger ones. In fact, you made your first matrix by concatenating its individual elements. The pair of square brackets, [ ], is the concatenation operator. For an example, start with the matrix m and form
>> r = [m m+32; m+48 m+16]
Note how we didn't use the semi-colon separator throughout - only after m+32 - a space is left between the others. How do you think the semicolon and space separators work?

Deleting rows and columns
You can delete rows and columns from a matrix using just a pair of square brackets. Start with
x = m;
Then, to delete the second column of m, use
x(:,2) = []
This changes x to
x =
1 3
4 6
7 9

Exercise: Delete the second row of m and store it in a matrix z.

Other useful commands
There are too many matrix commands to list and you are encouraged to browse the help facility to see what is available. Some of the more useful ones are listed below.
mean, sum, '. ' is the transpose operator.
Exercise: What is the result of m' ?

It is worth looking at a function like mean in more detail. If we ask for the mean of m:
>> mean(m)
we get the mean in each column. But suppose we want the mean in each row instead? There are two ways to achieve this. One is to take the mean of the transpose of m:
>> mean(m')
The other is to read the help file on mean and note that it takes an optional second argument which indicates the dimension along which the mean is to be taken (2, here).
Many functions operate in a similar fashion.

Strings
You will not need to use strings much for your project, but there are a few useful commands to know about. First, strings are represented by enclosing the characters in single quotes:
>> data= 'ocr5.dat';
Strings are just matrices (vectors of characters, in fact), so we can use the usual operations to manipulate them. e. g. use the matrix creation command for concatenation:
>> newstring = [' this file is called ' data]
this file is called ocr5.dat
If you need to get numeric quantities printed out, you should use the function num2str which converts numbers to strings:
>> newerstring = [' file size = ' num2str(fsize)];
Leaving out the semicolon is an easy way to display the value of a variable, as we have seen, but it is a bit untidy. A better way is to use the disp command, which displays the string you give it as input, but on a single line without the usual ' variable name = ' part.
>> disp([' file size = ' num2str(fsize)])
file size = 13456

Session exercise

  1. Generate a time vector t which begins at 0 and ends at 2 pi. t should have an increment of 0.01 pi.
  2. Calculate the sine of the time vector. You will not need a for loop. Use sin in the same manner as mean.
  3. Plot the sine wave using plot. If you do not know how to use this, use help. Note: your x axis must be scaled correctly (ie 0 to 6.3)

Next session: control structures (for, while and if).

Acknowledgements: Parts of this session originate from a MATLAB introduction written by Martin Cooke.

Session 1 | Session 2 | Session 3 | Session 4