HET419: Computer Laboratory 1

Introduction to MATLAB
This computer laboratory is aimed at obtaining some familiarity with the MATLAB numerical computation 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 manipulations 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

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 .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.

1 .3] x = 1 >> | which is a 1×3 matrix.operation MATLAB symbol example addition a + b subtraction a − b multiplication a × b division a ÷ b exponentiation ab + * \ or / ^ 3 + 2 16.20 4. 2 3 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 = 5 >> | To define a row vector x one could type: >> x = [1.2.2*6.18^3.7 56/8 = 86 2.

g >> y = [0 x] y = 0 1 2 3 3] 2 4 • 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   4 4 7 2 5 8 4  3 6  9  1  3 5  2 4  6 . • elements in a matrix are selected and modified according to the conventional indice (row then column) e.2.2. 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 x could be defined as x = [1 2 ( indicates whitespace).4]. • elements in a row may also be separated by one or more whitespaces e.1) ans = 1 • matrices can be defined using matrices that have already been defined e. one could type: >> A = [1. clear without any arguments clears all defined matrices.g >> A(1.3].g >> clear A. ordered conventionally as row by column.2. A = [1.3.g x = [1.g A could have been defined as >> A = [1 2 3 4] • defined variables (matrices) can be listed using the command who.3. • rows in a matrix can be separated by semicolons or a newline e.To define a 2×2 matrix.4] A = 1 3 >> | note: • multiple commands can be written on the same line by separating with a comma e.

3 and B(m. in the reference or definition of a matrix.:) for m = 1.4 ? From the last result deduce what the colon operator does. v are arbitrary real numbers ? A further use of the colon operator is to select a submatrix from another matrix. calling it submatrix_B3.:) >> submatrix_B2 = B(:.23 and C4 = 10:-1:0 ? In general what does x = t:u:v where t. note: Be careful to observe the different syntax of the : and . For example what is the result of performing the following ? >> C1 = 1:8 E7 E8 What about C2 = 1:2:8... E6 The colon operator (:) is also used to generate sequences in order to define new matrices.1:2) E10 Define the following matrix.. u. E9 What is the result of executing the following two commands: >> submatrix_B1 = B(1:2.3 E2 The colon operator Define the following matrix within MATLAB −1  1 B=  1 0   0 0 1 0   −1 0  0 2 E3 E4 E5 What is the result of executing the command B(:. in terms of the previously defined matrix B.1) ? What is obtained by executing B(:. C3 = 1:0.5:9.n) for n = 1. 1 −1 0 0 4 Elementary plotting Define the matrix 1 1 −1 −1 1 −1 1 −1 S= 5 ..

-2. axis([-2. separating individual commands) ? >> plot(S(1.S(2. 0). yvector1 .:). yvectorn . xvectorn . • 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. note: • the general form for the plot command is plot(xvector1 . 5 Matrix and scalar operations MATLAB distinguishes between an array operation and a matrix operation.. 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. 2]).:). By using the result of E13 plot both the outline of the square and the location of its vertices on the same graph.E11 What is the outcome of entering the following command (note the .. . options1 . 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.’yo’). An array operation is performed element-by-element. For example define the two row vectors b c = = 1 4 2 5 3 6 4 7 6 . 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.

point/line type point circle x-mark plus star solid line dotted line dashed line dash-dot line option symbol .0.c • b.c) 7 .*c • b. and is it commutative ? >> b1 = dot(b. second and eighth calculation ? What do the last two commands define ? What operation does the following command correspond to.^3 • 2. o x + * : --.^c • c.^b • 3*b • b’ • c’ E15 E16 E17 Why can the period be omitted in the first. and is the operation commutative ? >> B1 = b*B E18 What vector operation does the following command correspond to. colour yellow magenta cyan red green blue white black option symbol y m c r g b w k 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.

grid By defining two vectors e1 e2 = = 1 1 1 −1 8 .T(2.T(1.’r-’).5 −0.:).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.:).5 −2 1 E19 Calculate • DE • ED E20 E21 What is E in relationship to D ? What is D in relationship to E ? From this last result determine what the following functions in MATLAB compute inv(D) inv(E) 6 Eigenvalues and eigenvectors Define 5 3 3 5 F= E22 Calculate T = F S.’y-’.:).:).S(2. What are the dimensions of T ? By calculating F . axis([-10 10 -10 10]). where S is the modified matrix of E13 .Define D E = = 2 4 1 3 1.

The corresponding x = 0 solutions are called eigenvectors (or characteristic vectors). [0 e2(2)]. [0 te1(2)]. 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. From the previous plot determine the eigenvalues corresponding to e1 and e2 respectively. Note that the trivial solution x = 0 exists for all values of λ. not lying along the diagonal vertices of the square. Values of λ for which the above equation has a solution for x = 0 are called eigenvalues (or characteristic values) of A. 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.’y-’) te2(1)]. Sometimes you may see this equation referred to as the definition of the right eigenvector.’r-’) e2(1)].’r-’) e1(1)]. A is a square (i. x is a vector of length n and λ is a scalar that is in general complex.e n × n) matrix. It is shown in most elementary texts on linear algebra that the eigenvectors form a linearly independent set. [0 e1(2)]. 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. [0 te2(2)].e n y= i=1 ci xi 9 . Thus F e1 F e2 E24 = = λ 1 e1 λ 2 e2 Convince yourself that any other vector. is not simply scaled by F. e1 and e2 are called eigenvectors and the associated scaling factors under this transformation are called eigenvalues. E26 Is α e1 an eigenvector of F for any α = 0 ? Generalise this result for the eigenvector x. The above equations can be more compactly written as E25 A x = λx (1) and defines an eigenvalue problem.’y-’) Note that under the linear transformation F e1 and e2 become scaled versions of themselves.E23 evaluate te1 te2 = = F e1 F e2 Plot the resulting vectors on the previous graph by executing the following sequence of commands >> >> >> >> >> hold on plot([0 plot([0 plot([0 plot([0 te1(1)].

.. ··· a1n a2n . .. . E30 10 .e x = 0) if and only if the corresponding determinant of the coefficient matrix is zero i. . . How would you calculate the eigenvector corresponding to a particular eigenvalue ? (Hint: use equation (1) ). . By remembering that the determinant for a 2 × 2 matrix is a11 a21 a12 a22 det = a11 a22 − a21 a12 E28 E29 Calculate the characteristic polynomial corresponding to F. ··· 0 0 . Show that the roots of this characteristic polynomial correspond to the eigenvalues that you found in exercise E25 . . . . . E27 Show that any linear transformation A y can be written as n Ay = i=1 λi ci xi By defining the following diagonal matrix (called an identity matrix)  1 0 .where the ci are arbitrary constants to be chosen. 0 ··· ··· . ann − λ D(λ) = det (A − λ I) = = 0 (3) D(λ) is called the characteristic determinant. . . 0 0 1 . By developing D(λ) we obtain a polynomial of n-th degree in λ called the characteristic polynomial corresponding to A. . . an2 ··· ··· . an1 a12 a22 − λ .e a11 − λ a21 . 1        I=  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.

Simulink is called from within MATLAB by typing >> simulink After a short period a Simulink Library Browser window opens. Sum Copy the following from the Sources Library: Sine Wave. Try the following commands >> eig(F) >> [V. Constant Copy the following from the Sinks library: Scope 11 .D] = eig(F) E31 E32 What are the dimensions of V and D ? What do V and D represent ? 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 ). and thus places the user one step removed from the procedural programming language framework of MATLAB. Select from the menu bar File → New → Model to open a new model window. The block parameters can be set by right clicking on the object and selecting block name parameters. It enables the simulation and modelling of dynamical systems using a graphical interface.e outputs can be mapped to inputs) by clicking on one connecting point (indicated by a > or <) and dragging to another connecting point. 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. >> poly(F) >> roots(poly(F)) 7 Simulink Simulink is a software package typically run from within the MATLAB software environment.Fortunately MATLAB has built in functions for calculating eigenvalues and eigenvectors of an arbitrary matrix. Blocks can be connected (i. Copy the following objects from the Math Operations library to the new model window: Gain. The following example illustrates some of the basic operating principles of Simulink by detailing the steps needed to create a Fahrneheit to Celsius converter.

Gain: connect its output to one of the inputs of Sum. 3. Double click Scope to display it. Constant: connect its output to the second input of Sum. Sum Copy the following from the Sources Library: Step Copy the following from the Sinks library: Scope Connect the blocks as follows: 12 . Set the gain of Gain to 9/5. note: • to autoscale the output of Scope select the binocular icon in the Scope display window. Scope: connect the output of Sum to the input of Scope. Set Sine Wave amplitude to 10. Sine Wave: connect its output to the input of Gain. 2. 4. E33 Select Simulation → Start. Copy and Paste circuit and Scope output into your report. Simulink is also able to solve time-dependent differential equations. So far we have used Simulink to perform a rather straightforward functional mapping. 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 1 t<0 t≥0 u(t) = 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. Choose from the menu bar of the new simulation window Simulation → Simulation parameters and set the stop time to 10. Set Constant’s constant to 32.Connect the blocks and set their parameters as follows: 1.

Sum ++ Step 1 s Integrator Scope -2 Gain Figure 2: note: • right-click on the Gain block and select Format → Flip block to orient in the indicated direction. 13 . E34 Run the simulation and copy the output of the Scope to your report. • to get the extra connection from the Integrator block to the Gain block hold Ctrl down as you draw the line.