Introduction To Matlab
Introduction To Matlab
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:
190
>> |
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:
2
operation MATLAB symbol example
addition a + b + 3 + 2
subtraction a − b - 16.1 - 20
multiplication a × b * 4.2*6.7
exponentiation ab ^ 2.18^3.21
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 =
>> |
>> x = [1,2,3]
x =
1 2 3
>> |
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
1 1 2 3 1 2
2 4 5 6 3 4
4 7 8 9 5 6
4
3 The colon operator
−1 0 0
1 1 0
B=
1
−1 0
0 0 2
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
A further use of the colon operator is to select a submatrix from another matrix.
E10 Define the following matrix, calling it submatrix_B3, in terms of the previously defined matrix B.
µ ¶
1 0
−1 0
4 Elementary plotting
µ ¶
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) ?
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:
>> 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.
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
dash-dot line -.
Table 2: Plot options are specified by any combination of symbols from the left or right columns
• 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 ?
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
E21 From this last result determine what the following functions in MATLAB compute
inv(D)
inv(E)
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 ?
µ ¶
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.
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.
n
X
Ay = λi ci xi
i=1
1 0 ··· 0
0 1 ··· 0
I= .. .. ..
..
. . . .
0 0 ··· 1
(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.
µ ¶
a11 a12
det = a11 a22 − a21 a12
a21 a22
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)
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
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
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
½
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
Gain, Sum
Step
Scope
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