You are on page 1of 44

LAB 2 MATLAB BASICS

CE889 ARTIFICIAL NEURAL NETWORKS


Introduction to MATLAB

Head of Module : Professor Hani Hagras


Lab Assistants :
Aysenur Bilgin (abilgin@essex.ac.uk)
Andrew Starkey (astark@essex.ac.uk)

What is MATLAB?

MATLAB (short for MATrix LABoratory) is a language for technical


computing, developed by the Mathworks, Inc.

It provides a single platform for computation, visualization, programming and


software development and facilitates to analyze data, develop algorithms,
create models and applications.

All problems and solutions in MATLAB are expressed in notation used in linear
algebra and essentially involve operations using matrices and vectors.

Specific applications are collected in packages referred to as toolbox.

Examples of toolboxes: Statistics, Neural Networks, Fuzzy Logic, Control System,


Computer Vision, Optimization, and several other fields of applied science and
engineering.

Getting started

Open Matlab R2012a.


The MATLAB desktop appears in its default layout, and it contains other
windows.
The major tools within or accessible from the desktop are:

Help browser

Workspace

Explore data that


you create or
import from files.

Current folder
Access your files.

Command window

Enter commands at the command line, indicated by


the prompt (>>).

Command history

Start button

View or rerun commands


that you entered at the
command line.

Getting started

Alternatively, open Matlab R2013a.


The MATLAB desktop appears in its default layout, and it contains other
windows.
The major tools within or accessible from the desktop are:

Help browser

Workspace

Explore data that


you create or
import from files.

Current folder
Access your files.

Command window

Enter commands at the command line, indicated by


the prompt (>>).

Command history
View or rerun commands
that you entered at the
command line.

MATLAB as a numerical calculator

For a simple interactive calculation, just type the expression you want to
evaluate. For example, calculate the expression 1 + 2 * 3.
Type it at the prompt command (>>) as follows:
>> 1+2*3
ans =
7

Note that if you do not specify an output variable, MATLAB uses a default
variable ans, short for answer, to store the results of the current calculation.
Also, the variable ans is overwritten, if it already exists.

Alternatively, you may assign a value to a variable or output argument name.


For example, following will result in x being given the value 1 + 2 * 3 = 7. This
variable name can always be used to refer to the results of the previous
computations.
>> x = 1+2*3

x =
7

MATLAB as a numerical calculator

Once a variable has been created, it can be reassigned.


Also, you can suppress the numerical output by putting a semicolon (;) at the
end of the line. Then the sequence of commands looks like this:
>> t = 5;
>> t = t+1
t =
6

If an expression is entered incorrectly, MATLAB will return an error message.


For example, leave out the multiplication sign, *, in the following expression:
>> x = 10;
>> 5x
5x
|
Error: Unexpected MATLAB expression.

MATLAB as a numerical calculator

To make corrections,
o
o

Retype the expressions. But if the expression is lengthy, chances are high to make
more mistakes by typing second time.
Recall a previously typed command with the up-arrow key . When the command is
displayed at the command prompt, it can be modified if needed.

It is possible to enter multiple statements per line by using commas (,) or


semicolons (;).

Note that commas (,) allow multiple statements per line without suppressing
the output.
>> a=7; b=cos(a), c=cosh(a)
b =
0.7539
c =
548.3170

MATLAB as a numerical calculator

The hierarchy of operations are as follows:


1. Exponentiations
2. Multiplications and divisions
3. Additions and subtractions

However, the standard order of precedence of arithmetic operations can be


changed by inserting parentheses.

For example, the result of 1+2*3 is quite different than the similar expression with
parentheses (1+2)*3.
>> 1+2*3

ans =

>> (1+2)*3
while

Expression

1
3+22

2
5

6
7

+ can be represented in MATLAB as follows:

>> 1/(3+2^2)+2/5*6/7
ans =
0.4857

ans =

>> 1/3+2^2+(2/5)*(6/7)
while

ans =
4.6762

MATLAB Help

All MATLAB functions have supporting documentation that includes examples


and describes the function inputs, outputs, and calling syntax. There are
several ways to access this information from the command line:
o

Open the function documentation in a separate window using the doc command.
>> doc mean

Display function hints (the syntax portion of the function documentation) in the
Command Window by pausing after you type the open parentheses for the function
input arguments.
>> mean(

View an abbreviated text version of the function documentation in the Command


Window using the help command.
>> help mean

MATLAB Help

Another way to get help is to use the lookfor command which differs from the
help command as follows:
o
o

The help command searches for an exact function name match.


The lookfor command searches the quick summary information in each function for a
match.

Suppose that you are looking for a function to take the inverse of a matrix.
Since MATLAB does not have a function named inverse, the command help
inverse will produce nothing.
>> help inverse
inverse not found.
Use the Help browser search field to search the documentation, or
type "help help" for help command options, such as help for methods.

On the other hand, the command lookfor inverse will produce detailed
information, which includes the function of interest, inv.
>> lookfor inverse
inverter
invhilb
ipermute
acos
acosd
acosh

inv

Inverses of Matrices
Inverse Hilbert matrix.
Inverse permute array dimensions.
Inverse cosine, result in radians.
Inverse cosine, result in degrees.
Inverse hyperbolic cosine.

- Matrix inverse.

Mathematical functions

There is a long list of mathematical functions that are built into MATLAB.

These functions are called built-ins. Many standard mathematical functions,


such as sin(), cos(), tan(), , ln(), are evaluated by the functions sin, cos,
tan, exp, and log respectively in MATLAB. (See MATLAB help for more
information).

In addition to the elementary functions, MATLAB includes a number of


predefined constant values. A list of the most common values are:

pi: The number, = 3.1415

o
o
o

i, j: The imaginary unit , 1


Inf: The infinity,
NaN: Not a number

Example expressions:
o

The value of the expression = sin() + 10 2 , for a = 5, x = 2, and y = 8 is


computed by:
>> a = 5; x = 2; y = 8;
>> y = exp(-a)*sin(x)+10*y^2
y =

640.0061

Mathematical functions

Example expressions:
o

Natural logarithm
>> log(142)
ans =
4.9558

Decimal logarithm (base 10)


>> log10(142)
ans =
2.1523

Sine function
>> sin(pi/4)
ans =
0.7071

Exponential function
>> exp(10)
ans =
2.2026e+04

Managing the workspace

Some useful commands in MATLAB:


o
o
o
o
o

To clear the Command Window, type clc


To abort a MATLAB computation, type ctrl-c
To continue a line, type . . .
To clear all variables from the workspace and free up system memory, type clear
To display a list of the variables currently in the memory, type who
>> who
Your variables are:
a

ans

To get more details about the variable which include size, space allocation, and
class of the variables, type whos
>> whos
Name
a
b
c

Size

Bytes

Class

1x1
100x100
1x1

8
80000
8

double
double
double

Attributes

Vectors and Matrices

Remember MATrix LABoratory: While other programming languages mostly


work with numbers one at a time, MATLAB is designed to operate primarily on
whole matrices and arrays.

Variables in MATLAB are just like variables in any other programming language
(C, C++ etc.) Only difference is that you do not have to define them by
indicating the type etc.

Variable names can be used to refer to a single number (a scalar), a set of


numbers (a vector) or an array of numbers (a matrix).

Vectors are matrices having a single row (a row vector), or a single column (a
column vector).

Put together, all MATLAB variables are multidimensional arrays, no matter what
type of data. A matrix is a two-dimensional array often used for linear algebra.

Vectors and Matrices

The simplest way to create a matrix in MATLAB is to use the matrix constructor
operator, [ ].

Create a row or column vector by entering elements within the brackets.


Separating each element with:
o

comma or space results in a row vector, eg. [E1, E2, ..., Em] or [E1 E2 ... Em]
>> a = [1 2 3 4]
a =
1

semicolon results in a column vector, eg. [E1; E;...; Em] or [E1 E2 ... Em]

>> a = [1; 2; 3; 4]
a =
1
2
3
4

Vectors and Matrices

Vectors can also be created by incrementing a starting value with a constant


quantity.
For example, following expression creates a row vector, with the first element
being 0, each element incremented by 2 until the final value of 10.
>> r = [0:2:10]
r =
0

10

It is possible to index specific parts of a vector.

For example, to get the third element in the vector r:


>> r(3)

ans =
4

Vectors and Matrices

Matrix is a 2-dimentional array which has multiple columns and/or rows.

To create a matrix that has multiple rows, separate the rows with semicolons.
A = [row1; row2; ...; rown]

The following example constructs a 4 row, 5 column (or 4-by-5) matrix of


numbers.

>> A = [12 62 93 -8 22; 16 2 87 43 91; -4 17 -72 95 6; 10 25 6 -11 -30]


A =
12
16
-4
10

62
2
17
25

93
87
-72
6

-8
43
95
-11

22
91
6
-30

Vectors and Matrices

Alternatively, a matrix can be created as follows:


>> B = [0:2:10; 1:2:11]
B =
0
1

2
3

4
5

6
7

8
9

10
11

Individual elements of the matrix, for instance the element in the 2nd row, 5th
column can be accessed using the notation:
>> B(2,5)
ans =
9

Vectors and Matrices

MATLAB has a number of functions that create different kinds of matrices some
of which are specialized matrices. The functions shown below create matrices
for more general use:
>> ones(2,4)
ans =

ones: Create a matrix or array of all ones.

1
1

1
1

1
1

1
1

0
1
0

0
0
1

>> zeros(1,4)
ans =

zeros: Create a matrix or array of all zeros.

>> eye(3)

eye: Create an identity matrix with 1's on


the diagonal and 0's elsewhere.

ans =
1
0
0

Vectors and Matrices

MATLAB has a number of functions that create different kinds of matrices some
of which are specialized matrices. The functions shown below create matrices
for more general use:
>> diag([4 5 6])
ans =

diag: Create a diagonal matrix from a vector

4
0
0

0
5
0

0
0
6

>> rand(4,2)

rand: Create a matrix or array of uniformly


distributed random numbers.

randn: Create a matrix or array of normally


distributed random numbers.

ans =
0.8147
0.9058
0.1270
0.9134

0.6324
0.0975
0.2785
0.5469

>> randn(4,2)
ans =
3.5784
2.7694
-1.3499
3.0349

0.7254
-0.0631
0.7147
-0.2050

Vectors and Matrices

When entering signed numbers into a matrix, make sure that the sign
immediately precedes the numeric value.
>> A = [9 +3 -0.5]

>> A = [9+3-0.5]
while

A =
9.0000

3.0000

A =

-0.5000

11.5000

Note the change in the following matrices:

>> A = [11 -2 -20; 3 +4 -6; 21 +20 +2]

>> A = [11-2-20; 3+4-6; 21+20+2]

A =

A =
while
11
3
21

-2
4
20

-20
-6
2

-11
1
43

Vector and Matrix Operations

The basic arithmetic operations +, -, *, / can be used for vectors and matrices.
These would generate corresponding output vectors or matrices.

For example, to add two vectors:


>> A = [1 2 3 4];
>> B = [5 6 7 8];
>> C = A + B
C =
6

10

12

Only vectors that have the same number of elements can be added or
subtracted. Similarly, two matrices with identical number of rows and columns
can be subtracted as follows:
>> A = [1:3:20; 21:3:40];
>> B = [2:3:20; 22:3:40];
>> C = A - B
C =
-1
-1

-1
-1

-1
-1

-1
-1

-1
-1

-1
-1

-1
-1

Vector and Matrix Operations

For matrix multiplication, use the * operator where the number of columns in
the first matrix should be equal to the number of rows in the second one.

>> A =[1 2 3; 4 5 6]

>> B = A'

>> C =A*B

A =

B =

C =

1
4

2
5

3
6

1
2
3

4
5
6

14
32

For element-wise multiplication, use the .* operator:


>> A= [1 2 3 4; 5 6 7 8]; B = [2 2 2 2; 3 3 3 3];
>> C = A .* B
C =
2
15

4
18

6
21

8
24

32
77

Vector and Matrix Operations

To determine the dimensions of a matrix or vector, use the size command.

For example:

>> A=[1 2 3; 4 5 6; 7 8 9; 10 11 12]


A =
1
4
7
10

2
5
8
11

3
6
9
12

>> size(A)
ans =
4

The answer represents the number of rows followed by the number of columns.
Alternatively,
>> [m,n]=size(A)

m =
4
n =
3

Vector and Matrix Operations

Matrix indexing: To access elements of matrices, we need two indices.

The element of row i and column j of the matrix A is denoted by A(i, j). Thus,
A(i, j) in MATLAB refers to the element of matrix A. The first index is the row
number and the second index is the column number.

For example, A(1,3) is an element of first row and third column.


>> A=[1 2 3;4 5 6;7 8 9;10 11 12]
A =
>> A(3,3) = 0

1
4
7
10
>> A(1,3)

2
5
8
11

3
6
9
12

A =

1
4
7
10

2
5
8
11

3
6
0
12

ans =
3

Correcting any entry is easy through indexing. Try to substitute A(3,3)=9 by


A(3,3)=0.

Vector and Matrix Operations

The colon operator can be used to pick out a certain row or column. For
example, the statement A(m:n, k:l) specifies rows m to n and column k to l.
Subscript expressions refer to portions of a matrix. For example, following shows
the second row elements of A.
>> A(2,:)
ans =
4

The colon operator can also be used to extract a sub-matrix from a matrix A.
Following (on the left below) is a sub-matrix with the last two columns of A.
>> A(:,2:3)

>> A(:,2)=[ ]

>> A

ans =

A =

A =

2
5
8
11

3
6
0
12

1
4
7
10

3
6
0
12

where

1
4
7
10

2
5
8
11

3
6
0
12

A row or a column of a matrix can be deleted by setting it to a null vector, [ ].


Above example (in the middle) shows the resulting matrix when the second
column is deleted.

Vector and Matrix Operations

Similarly, to delete a row of a matrix, use the empty vector operator.


>> A

>> A(3,:) = [ ]

A =

A =
1
4
10

where

1
4
7
10

3
6
0
12

In the example above, third row of matrix A is deleted. To restore the third row,
we use a technique for creating a matrix (on the left).
>> A = [A(1,:);A(2,:);[7 9];A(3,:)]

>> A = [A(:,1) [2 5 8 11]' A(:,2)]

A =

A =
1
4
7
10

3
6
12

3
6
9
12

1
4
7
10

2
5
8
11

3
6
9
12

After restoring the second column (on the right), matrix A is now restored to its
original form.

Vector and Matrix Operations

To extract a submatrix B consisting of rows 2 and 3 and columns 1 and 2 of the


matrix A, do the following:
>> A

>> B = A([2 3],[1 2])

A =

B =

where
4
7

2
5
8
11

3
6
9
12

To interchange rows 1 and 2 of A, use the vector of row indices together with
the colon operator.
>> C = A([2 1 3 4],:)

>> A

C =

A =

4
1
7
10

1
4
7
10

5
8

5
2
8
11

6
3
9
12

where

1
4
7
10

2
5
8
11

3
6
9
12

It is important to note that the colon operator (:) stands for all columns or all
rows.

Vector and Matrix Operations

To create a vector version of matrix A, an alternative is to use the keyword


end, which denotes the last index in the specified dimension.
For example,

>> A

>> A(2:end,2:end)

A =

ans =
5
8
11

6
9
12

where

1
4
7
10

2
5
8
11

3
6
9
12

Below example reverses the rows of the final column of matrix A.


>> A(end:-1:1,end)

>> A

ans =

A =

12
9
6
3

where

1
4
7
10

2
5
8
11

3
6
9
12

Vector and Matrix Operations

The transpose operation is denoted by an apostrophe or a single quote ('). It


flips a matrix about its main diagonal and it turns a row vector into a column
vector.
>> A

>> A'

For example,

A =

ans =
1
2
3

4
5
6

7
8
9

10
11
12

where

1
4
7
10

2
5
8
11

3
6
9
12

In other words, the transpose of m*n real matrix A is the n*m matrix that results
from interchanging the rows and columns of A.

Vector and Matrix Operations

Array (arithmetic) operations, are done element-by-element.

The period character, (.), distinguishes the array operations from the matrix
operations. However, since the matrix and array operations are the same for
addition (+) and subtraction (-), the character pairs (.+) and (.-) are not used.

For example, let A and B be two matrices of the same size with elements
= [ ]and = [ ]

Original matrices,

>> A=[1 2 3;4 5 6;7 8 9],B=[10 20 30;40 50 60;70 80 90]


A =
1
4
7

2
5
8

3
6
9

10
40
70

20
50
80

30
60
90

B =

Vector and Matrix Operations


>> C = A.*B
C =

Multiplication

10
160
490

40
250
640

90
360
810

>> D = B./A

D =

Division

10
10
10

Power

10
10
10

10
10
10

>> P = A.^E

>> E = ones(3)*2

P =

E =
1
16
49

4
25
64

9
36
81

where

2
2
2

2
2
2

2
2
2

Loops

The for ... end loop (very similar to C expression) is a simple command for
setting up a loop.

For example:

>> for i = 1:10;


a(i) = i*i;
end
>> a
a =

16

25

36

49

64

81

100

All statements between the for and the end statements will be executed as
per the command specifications. Example of a for loop where the increment is
not one (1) would be as follows:
>> for i = 1:3:20;
f = [f,i];
end
>> f
f =
1

10

13

16

19

Loops

The while ... end loop is used when the number of passes is not specified. The
looping continues until a stated condition is satisfied. The while loop has the
following form:

while expression statements end

The statements are executed as long as the expression is true.

For example:

>> x = 1;
>> while x <= 10;
x = 3*x
end

Conditional Statements

In MATLAB, you can conditionally execute sections by using the keyword if. The
syntax is as follows:

if ... end
if ... elseif ... end

For example:

>> if overallMean < .49


disp('Mean is less than expected')
elseif overallMean > .51
disp('Mean is greater than expected')
else
disp('Mean is within the expected range')
end

Plotting

To create two-dimensional line plots, use the plot function. It generates plots
for functions of one variable. (See help for complete details.)

For example, plot the value of the sine function for x on the interval [0,10] as
follows:
Plot of the Sine Function
1
0.8
0.6
0.4
0.2
sin(x)

>> x = [0:0.1:10];
>> y = sin(x);
>> figure(1):plot(x, y);
>> xlabel('x')
>> ylabel('sin(x)')
title('Plot
of
the
Sine
Function')

0
-0.2
-0.4
-0.6
-0.8
-1

5
x

10

You can print a plot using the Print Option under the File Menu in the Figure
Window.

Saving Data

The save command is used for saving data to disk.

For example, it is possible to save values of a matrix or vector as follows:


>> A=[1 2 3;4 5 6;7 8 9;10 11 12]
A =
1
4
7
10

2
5
8
11

3
6
9
12

>> save A

The above example will save the variable A from the current workspace in a
MATLAB formatted binary file (MAT-file) called A.mat which is the default
format.
>> save A.txt A -ascii

Alternatively, the variable can be saved in ASCII format in the file specified
(A.txt under the current directory) so that it can be read by other programs.

Loading Data

The load command is used for loading data from disk.

For example, it is possible to save all variables from the workspace in binary
MAT-file test.mat. Then, remove the variables from the workspace, and
retrieve the data with the load function.
>> save test.mat
>> clear
>> load test.mat

MATLAB Scripts

The simplest type of MATLAB program is called a script.

A script is a file with a .m extension that contains multiple sequential lines of


MATLAB commands and function calls. You can run a script by typing its name
at the command line.

To create a script, you can


o
o

Use the edit command (opens a blank file named myscript.m.)


Use the File -> New -> Script option (opens a blank file as Untitled)

>> edit myscript

MATLAB Scripts

For example, enter some code that plots a vector of random data in the editor
window.
n = 50;
r = rand(n,1);
plot(r)

Whenever you write code, it is a good practice to add comments that


describe the code. Add comments using the percent (%) symbol.
% Generate random data from a uniform distribution
n = 50;
r = rand(n,1);
plot(r)

Save the file in the current folder using the toolbar in the editor window or the
Save option in the File menu.

To run the script, type its name at the command line.


>> myscript

Solving Systems of Linear Equations

One of the most important problems in technical computing is the solution of


systems of simultaneous linear equations.

In matrix notation, the general problem takes the following form: Given two
matrices A and B, does there exist a unique matrix , so that = or =
?

To solve the set of following equations:


o
o
o

a1 x + b1 y + c1 z = d1
a2 x + b2 y + c2 z = d2
a3 x + b3 y + c3 z = d3

We set up the matrix form as follows:


o

=
P = [a1 b1 c1; a2 b2 c2; a3 b3 c3]
U = [x; y; z]
Q = [d1; d2; d3]

The solution of this system of equations is = 1

In MATLAB, this can be expressed as = () or alternatively, by using


the backslash \ operator as in = \Q

Solving Systems of Linear Equations

For example, solve the following system of equations:

In the symbolic form = , is the 3x3 coefficient matrix and is the 3x1
column vector on the right hand side.

Here are the three steps to follow:

>> A = [ 0 1 2; 1 2 1; 3 5 2]
A =

1.

Define the matrix - fill in the definition

0
1
3

1
2
5

2
1
2

>> B = [ 1; 3; 7]

2.

Define the column vector

B =
1
3
7

3.

Solve for using the backslash command

>> X=A\B
X =
-2.0000
3.0000
-1.0000

Exercises

Explore the MATLAB help to find


o
o
o
o
o
o
o
o

The maximum element of a vector


The minimum element of a vector
How to sort a vector
How to sort a matrix
The mean of a sample
How to plot the relationship between two variables

Anything of your interest/curiosity

References

MathWorks Documentation Center


<http://www.mathworks.co.uk/help/matlab/index.html>

MATLAB Help Documentation

Tutorial for CE889 Introduction to MATLAB

You might also like