You are on page 1of 13

HET419: Computer Laboratory 1

Introduction to MATLAB
This computer laboratory is aimed at obtaining some familiarity with the MATLAB numerical com-
putation environment which will form the basis for all subsequent numerical explorations involved in
the subject Physiological Modeling - HET419. This laboratory provides an introduction to the use of
MATLAB version 6.5.

The MATLAB environment was first developed to be a high level language for the numerical manipula-
tions involved in a wide variety of mathematical problems involving linear (matrix) algebra.

MATLAB was developed in the late 1970’s as an interactive front-end to the FORTRAN subroutine
libraries called LINPACK and EISPACK. The program was named MATLAB, for MATrix LABoratory.
Since its original development it has evolved into a comprehensive and sophisticated interactive system
and programming language for general scientific and technical computation. It is one of a variety of high
level computational mathematical tools that are widely used in teaching, research and education. Others
include Mathematica, Maple, and Macsyma.

Exercises that the student must answer are identified by a E1 ... E32 in the left hand margin. Answers
to these exercises are the basis for assessment of this laboratory.

Because of the history underlying its development matrices and arrays are at the heart of MATLAB as
all data is stored within MATLAB as arrays. Just like a calculator MATLAB is capable of doing simple
mathematics. For instance on executing MATLAB the user is presented with a window containing three
panes: workspace/current directory pane, a command history pane and a command window pane. A
screen snapshot of this shown in figure 1 on the next page.

>> is the command line prompt. Commands are entered on this line and then executed by hitting
ENTER . Thus to calculate 10 × 4 + 6 × 25 we would type:

>> 10*4 + 6*25


ans =

190

>> |

1 Saving data and MATLAB output

There are two major ways of saving information from a MATLAB session. To save all the variables and
their values on a disk in the A drive type (at the end of your session)

>> cd a:
>> save lab1

This saves all variables in MATLAB binary format in the file lab1.mat. At a later date the variables
can be restored by typing

1
Figure 1:

>> cd a:
>> load lab1

To save all terminal input and output of a MATLAB session as ASCII to a file called lab1out on the A
drive type the following before you want to begin recording output

>> cd a:
>> diary lab1out

These commands cannot restored to a new session unless you have written them in M-file.

note:

• to find help on a specific function or feature type

>> help function

• to find help on a keyword type

>> lookfor keyword

and then use help to examine individual entries

2
operation MATLAB symbol example

addition a + b + 3 + 2

subtraction a − b - 16.1 - 20

multiplication a × b * 4.2*6.7

division a ÷ b \ or / 56/8 = 8\56

exponentiation ab ^ 2.18^3.21

Table 1: Elementary binary operations in MATLAB

2 Variables

Variables are easily defined in MATLAB by assigning a value to any arbitrary string of characters. For
instance to define a scalar (a 1×1 matrix) a type:

>> a = 5
a =

>> |

To define a row vector x one could type:

>> x = [1,2,3]

x =

1 2 3

>> |

which is a 1×3 matrix.

3
To define a 2×2 matrix, ordered conventionally as row by column, one could type:

>> A = [1,2;3,4]

A =

1 2
3 4

>> |

note:

• multiple commands can be written on the same line by separating with a comma e.g x = [1,2,3], A = [1,2;3,4].
• elements in a row may also be separated by one or more whitespaces e.g x could be defined as xÃ=Ã[1Ã2ÃÃÃ3]
(Ã indicates whitespace).
• rows in a matrix can be separated by semicolons or a newline e.g A could have been defined as
>> A = [1 2
3 4]
• defined variables (matrices) can be listed using the command who, defined matrices and their sizes can be
listed using the command whos
• references to defined matrices can be removed from memory by using the command clear e.g >> clear A.
clear without any arguments clears all defined matrices.
• elements in a matrix are selected and modified according to the conventional indice (row then column) e.g

>> A(1,1)

ans =

• matrices can be defined using matrices that have already been defined e.g

>> y = [0 x]

y =

0 1 2 3

• additional elements can be added after the matrix has been defined e.g

>> y(5) = 4

y =

0 1 2 3 4

E1 Define the following matrices in MATLAB

     
1 1 2 3 1 2
 2   4 5 6   3 4 
4 7 8 9 5 6

4
3 The colon operator

E2 Define the following matrix within MATLAB

 
−1 0 0
 1 1 0 
B=
 1

−1 0 
0 0 2

E3 What is the result of executing the command B(:,1) ?

E4 What is obtained by executing B(:,n) for n = 1...3 and B(m,:) for m = 1...4 ?

E5 From the last result deduce what the colon operator does.

note: Be careful to observe the different syntax of the : and ; in the reference or definition of a matrix.

E6 The colon operator (:) is also used to generate sequences in order to define new matrices. For example
what is the result of performing the following ?

>> C1 = 1:8

E7 What about C2 = 1:2:8, C3 = 1:0.5:9.23 and C4 = 10:-1:0 ?

E8 In general what does x = t:u:v where t, u, v are arbitrary real numbers ?

A further use of the colon operator is to select a submatrix from another matrix.

E9 What is the result of executing the following two commands:

>> submatrix_B1 = B(1:2,:)


>> submatrix_B2 = B(:,1:2)

E10 Define the following matrix, calling it submatrix_B3, in terms of the previously defined matrix B.

µ ¶
1 0
−1 0

4 Elementary plotting

Define the matrix

µ ¶
1 −1 −1 1
S=
1 1 −1 −1

5
E11 What is the outcome of entering the following command (note the , separating individual commands) ?

>> plot(S(1,:),S(2,:),’yo’), axis([-2, 2, -2, 2]), grid on

E12 What is the result of repeating the last sequence of commands by

• replacing the argument ’yo’ with ’y-’


• omitting either the axis or grid on command
• augmenting with one or more of
xlabel(’the x axis’)
ylabel(’the y axis’)
title(’the plot title’)

E13 By adding additional elements to S and using a sequence of commands that have already been used plot
a square of dimension 2 units by 2 units centered on (0, 0).

note:

• the general form for the plot command is

plot(xvector1 , yvector1 , options1 , ..., xvectorn , yvectorn , optionsn )

which plots multiple data sets on the same graph


• the general form for the axis command is axis([xmin xmax ymin ymax ])
• the commands axis and grid act on the current plot.
• the command

>> hold on

freezes the current plot (including axes ranges and appearance of a grid) so that any subsequent plot
commands are to this frozen plot.

By using the result of E13 plot both the outline of the square and the location of its vertices on the
same graph.

5 Matrix and scalar operations

MATLAB distinguishes between an array operation and a matrix operation. An array operation is
performed element-by-element. To indicate that we want to perform an element-by-element binary
array operation we use one of the operators of Table 1 preceeded by a period. For example define the
two row vectors

¡ ¢
b = 1 2 3 4
¡ ¢
c = 4 5 6 7

6
point/line type option symbol colour option symbol

point . yellow y

circle o magenta m

x-mark x cyan c

plus + red r

star * green g

solid line - blue b

dotted line : white w

dashed line -- black k

dash-dot line -.

Table 2: Plot options are specified by any combination of symbols from the left or right columns

E14 What are the results of performing the following operations ?

• b + c
• b - c
• b.*c
• b./c
• b.^c
• c.^3
• 2.0.^b
• 3*b
• b’
• c’

E15 Why can the period be omitted in the first, second and eighth calculation ?

E16 What do the last two commands define ?

E17 What operation does the following command correspond to, and is the operation commutative ?

>> B1 = b*B

E18 What vector operation does the following command correspond to, and is it commutative ?

>> b1 = dot(b,c)

7
Define

µ ¶
2 1
D =
4 3
µ ¶
1.5 −0.5
E =
−2 1

E19 Calculate

• DE
• ED

E20 What is E in relationship to D ? What is D in relationship to E ?

E21 From this last result determine what the following functions in MATLAB compute

inv(D)

inv(E)

6 Eigenvalues and eigenvectors

Define

µ ¶
5 3
F=
3 5

E22 Calculate T = F S, where S is the modified matrix of E13 . What are the dimensions of T ? By calculating
F - F’ what does the result imply about F ?

Plot S and T on the same graph using a command of the form

>> plot(S(1,:),S(2,:),’y-’,T(1,:),T(2,:),’r-’), axis([-10 10 -10 10]), grid

By defining two vectors

µ ¶
1
e1 =
1
µ ¶
1
e2 =
−1

8
E23 evaluate

te1 = F e1
te2 = F e2

Plot the resulting vectors on the previous graph by executing the following sequence of commands

>> hold on
>> plot([0 te1(1)], [0 te1(2)],’r-’)
>> plot([0 e1(1)], [0 e1(2)],’y-’)
>> plot([0 te2(1)], [0 te2(2)],’r-’)
>> plot([0 e2(1)], [0 e2(2)],’y-’)

Note that under the linear transformation F e1 and e2 become scaled versions of themselves, the same
is not true of the location of any other points on the original square that do not correspond to one of the
vertices. e1 and e2 are called eigenvectors and the associated scaling factors under this transformation
are called eigenvalues. Thus

F e1 = λ 1 e1
F e2 = λ 2 e2

E24 Convince yourself that any other vector, not lying along the diagonal vertices of the square, is not simply
scaled by F.

E25 From the previous plot determine the eigenvalues corresponding to e1 and e2 respectively.

The above equations can be more compactly written as

A x = λx (1)

and defines an eigenvalue problem. A is a square (i.e n × n) matrix, x is a vector of length n and λ is a
scalar that is in general complex. Note that the trivial solution x = 0 exists for all values of λ. Values
of λ for which the above equation has a solution for x 6= 0 are called eigenvalues (or characteristic
values) of A. The corresponding x 6= 0 solutions are called eigenvectors (or characteristic vectors).
Sometimes you may see this equation referred to as the definition of the right eigenvector.

E26 Is α e1 an eigenvector of F for any α 6= 0 ? Generalise this result for the eigenvector x.

The eigenvectors represent the principle axes of transformation and correspond to the directions along
which the location of points are just scaled under a linear transformation. It is shown in most elementary
texts on linear algebra that the eigenvectors form a linearly independent set. This is noteworthy in
as much that any vector y having the same dimension as x can be represented as a linear combination
of the eigenvectors xi (in other words the eigenvectors represent a basis for an n-dimensional space) i.e

n
X
y= ci xi
i=1

9
where the ci are arbitrary constants to be chosen.

E27 Show that any linear transformation A y can be written as

n
X
Ay = λi ci xi
i=1

By defining the following diagonal matrix (called an identity matrix)

 
1 0 ··· 0
 0 1 ··· 0 
I= .. .. ..
 
.. 
 . . . . 
0 0 ··· 1

convince yourself that equation (1) can be rewritten as

(A − λ I) x = 0 (2)

By Cramer’s Theorem (a description of which can be found in any elementary textbook on linear algebra)
this homogeneous linear system has a non-trivial solution (i.e x 6= 0) if and only if the corresponding
determinant of the coefficient matrix is zero i.e

¯ ¯
¯ a11 − λ a12 ··· a1n ¯
¯ ¯
¯ a21 a22 − λ ··· a2n ¯
D(λ) = det (A − λ I) = ¯ .. .. .. ¯ = 0 (3)
¯ ¯
..
¯
¯ . . . . ¯
¯
¯ an1 an2 ··· ann − λ ¯

D(λ) is called the characteristic determinant. By developing D(λ) we obtain a polynomial of n-th
degree in λ called the characteristic polynomial corresponding to A.

By remembering that the determinant for a 2 × 2 matrix is

µ ¶
a11 a12
det = a11 a22 − a21 a12
a21 a22

E28 Calculate the characteristic polynomial corresponding to F.

E29 Show that the roots of this characteristic polynomial correspond to the eigenvalues that you found in
exercise E25 .

E30 How would you calculate the eigenvector corresponding to a particular eigenvalue ? (Hint: use equation
(1) ).

10
Fortunately MATLAB has built in functions for calculating eigenvalues and eigenvectors of an arbitrary
matrix. Try the following commands

>> eig(F)
>> [V,D] = eig(F)

E31 What are the dimensions of V and D ? What do V and D represent ?

E32 What do the following MATLAB commands give and what is the significance of the results ? (Hint:
compare the outcome of these commands with the results of E28 and E29 ).

>> poly(F)
>> roots(poly(F))

7 Simulink

Simulink is a software package typically run from within the MATLAB software environment. It enables
the simulation and modelling of dynamical systems using a graphical interface, and thus places the user
one step removed from the procedural programming language framework of MATLAB.

Simulink is called from within MATLAB by typing

>> simulink

After a short period a Simulink Library Browser window opens. Select from the menu bar File → New →
Model to open a new model window. The user can then drag blocks from the library browser window to
the new window by clicking either the left or right mouse button and dragging. Blocks can be connected
(i.e outputs can be mapped to inputs) by clicking on one connecting point (indicated by a > or <) and
dragging to another connecting point. The block parameters can be set by right clicking on the object
and selecting block name parameters.

The following example illustrates some of the basic operating principles of Simulink by detailing the steps
needed to create a Fahrneheit to Celsius converter.

Copy the following objects from the Math Operations library to the new model window:

Gain, Sum

Copy the following from the Sources Library:

Sine Wave, Constant

Copy the following from the Sinks library:

Scope

11
Connect the blocks and set their parameters as follows:

1. Sine Wave: connect its output to the input of Gain. Set Sine Wave amplitude to 10.

2. Gain: connect its output to one of the inputs of Sum. Set the gain of Gain to 9/5.

3. Constant: connect its output to the second input of Sum. Set Constant’s constant to 32.

4. Scope: connect the output of Sum to the input of Scope. Double click Scope to display it.

Choose from the menu bar of the new simulation window Simulation → Simulation parameters and
set the stop time to 10.

E33 Select Simulation → Start. Copy and Paste circuit and Scope output into your report.

note:

• to autoscale the output of Scope select the binocular icon in the Scope display window.

So far we have used Simulink to perform a rather straightforward functional mapping. Simulink is also
able to solve time-dependent differential equations. The following example illustrates how one would go
about solving

dy
= −2y + u(t)
dt

where u(t) is the unit step function and is defined as

½
0 t<0
u(t) =
1 t≥0

To solve this equation using simulink copy the following objects to a new model window: From the
Comtinuous library copy

Integrator

Copy the following objects from the Math Operations library

Gain, Sum

Copy the following from the Sources Library:

Step

Copy the following from the Sinks library:

Scope

Connect the blocks as follows:

12
Sum
1
++ s
Step Integrator Scope

-2

Gain

Figure 2:

note:

• right-click on the Gain block and select Format → Flip block to orient in the indicated direction.
• to get the extra connection from the Integrator block to the Gain block hold Ctrl down as you draw the
line.

E34 Run the simulation and copy the output of the Scope to your report.

13

You might also like