mathematically modeled area · 2013-11-07 · freshman-sophomore college level, and has a steeper...

83
COMPUTATIONAL METHODS FOR THE INTERDISCIPLINARY SCIENCES MATHEMATICALLY MODELED AREA Global Climate Change and the Spread of Infectious Diseases Supported by the W.M. Keck Foundation

Upload: others

Post on 25-Jul-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 1 of 83

COMPUTATIONAL METHODS FOR THE INTERDISCIPLINARY SCIENCES  

 

MATHEMATICALLY MODELED AREA

 

G l o b a l   C l i m a t e   C h a n g e   a n d   t h e   S p r e a d   o f   I n f e c t i o u s   D i s e a s e s  S u p p o r t e d   b y   t h e   W . M .   K e c k   F o u n d a t i o n  

Page 2: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 2 of 83

COMPUTATIONAL METHODS FOR THE INTERDISCIPLINARY SCIENCES

The Keck Training Program: An Interdisciplinary Research Training Program for Undergraduates

San Diego State University Summer 2012

Page 3: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 3 of 83

Table of Contents 1.  -­‐  PREFACE ........................................................................................................................... 4  

2.  -­‐  INTRODUCTION  TO  MATLAB ............................................................................................. 6  WHAT  IS  MATLAB?........................................................................................................................... 6  MATLAB  AT  SAN  DIEGO  STATE  UNIVERSITY ..................................................................................... 6  HOW  TO  COMPLETE  THE  MATLAB  EXERCISES................................................................................... 6  MATLAB  BASICS ............................................................................................................................... 7  PROGRAMMING  IN  MATLAB.......................................................................................................... 28  DATA  IMPORT  AND  EXPORT .......................................................................................................... 36  DATA  VISUALIZATION  IN  MATLAB.................................................................................................. 40  MESH  AND  SURFACE  PLOTS ........................................................................................................... 47  SPECIALIZED  GRAPHICS.................................................................................................................. 48  ADVANCED  TOPICS ........................................................................................................................ 54  ADDITIONAL  TOPICS ...................................................................................................................... 58  

3.  -­‐  CASE  STUDY  1:  The  Modeling  Process,  Proportionality,  and  Geometric  Similarity ........... 63  Proportionality/Geometric  Similarity  Modeling ............................................................................. 63  

4.  -­‐  Case  Study  #2  –  Basic  Bioinformatics............................................................................... 66  

5.  -­‐  Case  Study  #3  –  A  Measles  Model ................................................................................... 67  

6.  -­‐  Case  Study  #4  -­‐  Exploring  the  SIR  Model  Using  pplane8................................................... 68  

7.  -­‐  Case  Study  #5  –  Building  an  SIR  System  of  Differential  Equations.................................... 71  How  can  I  use  Differential  Equations  to  Build  a  Model? ................................................................. 71  Example:    The  Flu  SIR  Model .......................................................................................................... 72  

8.  -­‐  Case  Study  #6  –  BUILDING  AN  SIR  SYSTEM  USING  CELLULAR  AUTOMATA ....................... 79  

9.  -­‐  CLOSING  REMARKS  AND  REFERENCES............................................................................. 80  

10.  -­‐  ATTACHMENTS ............................................................................................................. 81  Attachment  ‘A’    -­‐  MATLAB  File  #1 .................................................................................................. 81  Attachment  ‘B’  –  MATLAB  File  #2................................................................................................... 82  

11.  -­‐  REFERENCES.................................................................................................................. 83  

Page 4: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 4 of 83

1. - PREFACE We reviewed the breadth of available literature, software, and texts dealing with computer modeling for understanding the spread of infectious diseases. With this information at hand we put together this document to introduce mathematical and computational approaches as they are applied to study the spread of a disease in a population. We then needed to select a software language in which students could develop these models during the short span of the summer program. The chosen software language was MATLAB (®The MathWorks, Inc., Natick, MA 01760). The proposed software offers the students various strengths for the implementation, simulation, and understanding of mathematical models that describe the spread of diseases in a population and provide a solid foundation of programming skills for other simulations in academic and research applications. The strengths of MATLAB include the ease of plotting program results, technical support via numerous examples through MathWorks, abundant pre-programmed functions, and its strength for advanced mathematical manipulations. However, MATLAB requires greater mastery of mathematics beyond the freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those students who are computationally inclined or those who wish to learn more about higher order programming. MATLAB will serve as a great stepping-stone towards high order programming languages such as C, C++ and FORTRAN. The main reason for developing and solving many mathematical equations is to try to learn something about an underlying physical process that the developed system of equations (or single equation) is supposed to model. Gaining an understanding of a complex process is usually accomplished by combining or building upon simpler and more basic models. The initial step in building a complex model could be as modest as creating a simple sketch with all its components represented by boxes and arrows showing the interactions between those different components. Building a basic understanding of the interactions between the different components of a system, the equations that describe them, and their solutions, is a crucial step toward the solution of complex realistic problems. Let’s take for example the case of a simple flu. Let’s assume we have a population of size N, where all members of the population are susceptible to acquiring a certain strain of flu. If one individual in the population is infected with this flu, as that one individual comes in contact with the susceptible individuals in the population they will acquire the flu at a particular rate. Once infected with the flu themselves, the individuals will interact with and infect others in the population. This process will continue until most of the individuals in the population have been exposed and infected with the flu. Subsequently all individuals who were infected will recover within a few days. Once recovered these individuals become immune to that particular strain of the flu virus. In this scenario we could at some point divide the population into three groups; those susceptible to the flu, those who are currently infected and those who have recovered and are thus now immune. We could perform this partitioning of the population on a daily or even hourly basis to track the changes in each of the groups as time changes. Therefore, initially we could create a graphical representation of our system to facilitate the understanding of the different interactions occurring and simplify the construction of our system of mathematical equations.

Page 5: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 5 of 83

If we wish to model the number of individuals in each of those three states at any given time we could make use of a mathematical model using a system of differential equations. Yet, first we would like to have a good understanding of the characteristics of our flu epidemic, this includes a knowledge of the rates of infection and recovery once an individual has been infected. These rates could be obtained experimentally or approximated based on historical data of similar or related flu outbreaks. Once a basic model has been established we can test our model and verify if it properly models the behavior we wish to analyze. Once a successful basic model has been established, it is possible to incorporate more complex characteristics into the model to make it more realistic. In the particular case of our flu model, these complex characteristics could include death, re-infection and so forth. This document will first introduce the basics of MATLAB and will provide some basic exercises so that you can become familiar with its many functions. Case studies are provided later in this document to help you not only put your newly gathered knowledge of MATLAB to work but to help you obtain a deeper understanding of the modeling process. Good luck and I hope this manual is helpful in this goal… This document was created for The Keck Training Program: An Interdisciplinary Research Training Program for Undergraduates at San Diego State University. A section of this document is partially based on a document created by Christos Xenophontos at Loyola University and was modified with permission. Other sections are based on those books listed on the references section. This document is intended to be for educational purposes only.

Page 6: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 6 of 83

2. - INTRODUCTION TO MATLAB

WHAT IS MATLAB? MATLAB, which stands for MATrix LABoratory, is a state-of-the-art mathematical software package, which is used extensively in both academia and industry. It is an interactive program for numerical computation and data visualization, which along with its programming capabilities provides a very useful tool for almost all areas of science and engineering. Unlike other mathematical packages, such as MAPLE or MATHEMATICA, MA TLAB cannot perform symbolic manipulations without the use of additional Toolboxes. It remains however, one of the leading software packages for numerical computation. As you might guess from its name, MATLAB deals mainly with matrices. A scalar is a 1-by-1 matrix and a row vector of length say 5, is a 1-by-5 matrix. We will elaborate more on these and other features of MATLAB in the sections that follow. One of the many advantages of MATLAB is the natural notation used. It looks a lot like the notation that you encounter in a linear algebra course. This makes the use of the program especially easy and it is what makes MATLAB a natural choice for numerical computations. The purpose of this tutorial is to familiarize the beginner to MATLAB, by introducing the basic features and commands of the program. It is in no way a complete reference and the reader is encouraged to further enhance his or her knowledge of MATLAB by reading some of the suggested references at the end of this guide.

MATLAB AT SAN DIEGO STATE UNIVERSITY The latest version of the MATLAB software can be obtain from the Technical Support office located in GMCS 111. A note from your research supervisor may be needed to obtain a copy of the software. Once you obtain a disk with a copy of the software install it in your computer. Double-click on the MATLAB icon and off you go ... The program will start in a new window and once you see the prompt (») you will be ready to begin ... The current (working) sub-directory is by default d:\Applications\matlabR14.

HOW TO COMPLETE THE MATLAB EXERCISES In the sections that follow, the MATLAB prompt (») will be used to indicate where the commands are entered. Anything you see after this prompt denotes user input (i.e. a command) followed by a carriage return (i.e. the “enter” key). Often, input is followed by output so unless otherwise specified the line(s) that follow a command will denote output (i.e. MATLAB’s response to what you typed in). MATLAB is case-sensitive, which means that a + B is not the same as a + b. Different fonts, like the ones you just witnessed, will also be used to simulate the interactive session. This can be seen in the example below: e.g. MATLAB can work as a calculator. If we ask MATLAB to add two numbers, we get the answer we expect. » 3 + 4 ans =

Page 7: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 7 of 83

7 As we will see, MATLAB is much more than a “fancy” calculator. In order to get the most out this tutorial you are strongly encouraged to try all the commands introduced in each section and work on all the recommended exercises. This usually works best if after reading this guide once, you read it again (and possibly again and again) in front of a computer.

MATLAB BASICS The basic features Let us start with something simple, like defining a row vector with components the numbers 1, 2, 3, 4, 5 and assigning it a variable name, say x. » x = [1 2 3 4 5] x= 1 2 3 4 5 Note that we used the equal sign for assigning the variable name x to the vector, brackets to enclose its entries and spaces to separate them. (Just like you would using the linear algebra notation). We could have used commas ( , ) instead of spaces to separate the entries, or even a combination of the two. The use of either spaces or commas is essential! To create a column vector (MATLAB distinguishes between row and column vectors, as it should) we can either use semicolons ( ; ) to separate the entries, or first define a row vector and take its transpose to obtain a column vector. Let us demonstrate this by defining a column vector y with entries 6, 7, 8, 9, 10 using both techniques. » y = [6;7;8;9;10] y = 6 7 8 9 10 y = [6,7,8,9,10] y = 6 7 8 9 10 » y' ans = 6 7 8 9 10

Page 8: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 8 of 83

Let us make a few comments. First, note that to take the transpose of a vector (or a matrix for that matter) we use the single quote ( ' ). Also note that MATLAB repeats (after it processes) what we typed in. Sometimes, however, we might not wish to “see” the output of a specific command. We can suppress the output by using a semicolon ( ; ) at the end of the command line. Finally, keep in mind that MATLAB automatically assigns the variable name ans to anything that has not been assigned a name. In the example above, this means that a new variable has been created with the column vector entries as its value. The variable ans, however, gets recycled and every time we type in a command without assigning a variable, ans gets that value. It is good practice to keep track of what variables are defined and occupy our workspace. Due to the fact that this can be cumbersome, MATLAB can do it for us. The command whos gives all sorts of information on what variables are active. » whos Name Size Elements Bytes Density Complex ans 5 by 1 5 40 Full No x 1 by 5 5 40 Full No y 1 by 5 5 40 Full No Grand total is 15 elements using 120 bytes A similar command, called who, only provides the names of the variables that are active. » who Your variables are: ans x y If we no longer need a particular variable we can “erase” it from memory using the command clear variable_name. Let us clear the variable ans and check that we indeed did so. » clear ans » who Your variables are: x y The command clear used by itself “erases” all the variables from the memory. Be careful, as this is not reversible and you do not have a second chance to change your mind. You may exit the program using the quit command. When doing so, all variables are lost. However, invoking the command save filename before exiting causes all variables to be written to a binary file called filename.mat. When we start MATLAB again, we may retrieve the information in this file with the command load filename. We can also create an ascii (text) file containing the entire MATLAB session if we use the command diary filename at the beginning and at the end of our

Page 9: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 9 of 83

session. This will create a text file called filename (with no extension) that can be edited with any text editor, printed out etc. This file will include everything we typed into MATLAB during the session (including error messages but excluding plots). We could also use the command save filename at the end of our session to create the binary file described above as well as the text file that includes our work. One last command to mention before we start learning some more interesting things about MATLAB, is the help command. This provides help for any existing MATLAB command. Let us try this command on the command who. » help who WHO List current variables. WHO lists the variables in the current workspace. WHOS lists more information about each variable. WHO GLOBAL and WHOS GLOBAL list the variables in the global workspace. Try using the command help on itself! On a PC, help is also available from the Window Menus. Sometimes it is easier to look up a command from the list provided there, instead of using the command line help. Vectors and matrices We have already seen how to define a vector and assign a variable name to it. Often it is useful to define vectors (and matrices) that contain equally spaced entries. This can be done by specifying the first entry, an increment, and the last entry. MATLAB will automatically figure out how many entries you need and their values. For example, to create a vector whose entries are 0, 1, 2, 3, ..., 7, 8, you can type » u = [0:8] u = 0 1 2 3 4 5 6 7 8 Here we specified the first entry 0 and the last entry 8, separated by a colon ( : ). MATLAB automatically filled-in the (omitted) entries using the (default) increment 1. You could also specify an increment as is done in the next example. To obtain a vector whose entries are 0, 2, 4, 6, and 8, you can type in the following line: » v = [0:2:8] v = 0 2 4 6 8 Here we specified the first entry 0, the increment value 2, and the last entry 8. The two colons ( : ) “tell” MATLAB to fill in the (omitted) entries using the specified increment value. MATLAB will allow you to look at specific parts of the vector. If you want, for example, to only look at the first 3 entries in the vector v, you can use:

Page 10: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 10 of 83

» v(1:3) ans = 0 2 4 Note that we used parentheses, instead of brackets, to refer to the entries of the vector. Since we omitted the increment value, MATLAB automatically assumes that the increment is 1. The following command lists the first 4 entries of the vector v, using the increment value 2: » v(1:2:4) ans = 0 4 Defining a matrix is similar to defining a vector. To define a matrix A, you can treat it like a column of row vectors. That is, you enter each row of the matrix as a row vector (remember to separate the entries either by commas or spaces) and you separate the rows by semicolons ( ; ). » A = [1 2 3; 3 4 5; 6 7 8] A = 1 2 3 3 4 5 6 7 8 We can avoid separating each row with a semicolon if we use a carriage return instead. In other words, we could have defined A as follows » A = [ 1 2 3 3 4 5 6 7 8] A = 1 2 3 3 4 5 6 7 8 which is perhaps closer to the way we would have defined A by hand using standard linear algebra notation. You can refer to a particular entry in a matrix by using parentheses. For example, the number 5 lies in the 2nd row, 3rd column of A, thus » A(2,3) ans = 5

Page 11: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 11 of 83

The order of rows and columns follows the convention adopted in standard linear algebra notation. This means that A(2,3) refers to the number 5 in the above example and A(3,2) refers to the number 7, which is in the 3rd row, 2nd column. Note MATLAB’s response when we ask for the entry in the 4th row, 1st column. » A(4,1) ??? Index exceeds matrix dimensions. As expected, we get an error message. Since A is a 3-by-3 matrix, there is no 4th row and MATLAB realizes that. The error messages that we get from MATLAB can be quite informative when trying to find out what went wrong. In this case MATLAB told us exactly what the problem was. We can “extract” submatrices using a similar notation as above. For example to obtain the submatrix that consists of the first two rows and last two columns of A we type » A(1:2,2:3) ans = 2 3 4 5 We could even extract an entire row or column of a matrix, using the colon ( : ) as follows. Suppose we want to get the 2nd column of A. We basically want the elements [A(1,2) A(2,2) A(3,2)]. We type » A(:,2) ans = 2 4 7 where the colon was used to tell MATLAB that all the rows are to be used. The same can be done when we want to extract an entire row, say the 3rd one. » A(3,:) ans = 6 7 8 Define now another matrix B, and two vectors s and t that will be used in what follows. »B = [ -1 3 10 -9 5 25 0 14 2] B = -1 3 10

Page 12: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 12 of 83

-9 5 25 0 14 2 » s = [-1 8 5] s = -1 8 5 » t = [7;0;11] t= 7 0 11 The real power of MATLAB is the ease in which you can manipulate your vectors and matrices. For example, to subtract 1 from every entry in the matrix A we type » A-1 ans = 0 1 2 2 3 4 5 6 7 It is just as easy to add (or subtract) two compatible matrices (i.e. matrices of the same size). » A+B ans = 0 5 13 -6 9 30 6 21 10 The same is true for vectors. » s-t ??? Error using ==> - Matrix dimensions must agree. This error was expected, since s has size 1-by-3 and t has size 3-by-1. We will not get an error if we type » s-t' ans = -8 8 -6 since by taking the transpose of t we make the two vectors compatible.

Page 13: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 13 of 83

We must be equally careful when using multiplication. » B*s ??? Error using ==> * Inner matrix dimensions must agree. » B*t ans = 103 212 22 Another important operation that MATLAB can perform with ease is “matrix division”. If M is an invertible† square matrix and b is a compatible vector then x = M\b is the solution of M x = b and x = b/M is the solution of x M = b. Let us illustrate the first of the two operations above with M = B and b = t. » x=B\t x= 2.4307 0.6801 0.7390 x is the solution of B x = t as can be seen in the multiplication below. » B*x ans = 7.0000 0.0000 11.0000 Since x does not consist of integers, it is worthwhile mentioning here the command format long. MATLAB by default only displays four digits beyond the decimal point of a real number unless we use the command format long, which tells MATLAB to display more digits. » format long » x x= 2.43071593533487 0.68013856812933 0.73903002309469 On a PC the command format long can also be used through the Windows Menus. There are many

Page 14: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 14 of 83

times when we want to perform an operation on every entry in a vector or matrix. MATLAB will allow us to do this with “element-wise” operations. For example, suppose you want to multiply each entry in the vector s with itself. In other words, suppose you want to obtain the vector s2 = [s(1)*s(1), s(2)*s(2), s(3)*s(3)]. The command s*s will not work due to incompatibility. What is needed here is to tell MATLAB to perform the multiplication element-wise. This is done with the symbols ".*". In fact, you can put a period in front of most operators to tell MATLAB that you want the operation to take place on each entry of the vector (or matrix). » s*s ??? Error using ==> * Inner matrix dimensions must agree. » s.*s ans = 1 64 25 The symbol " .^ " can also be used since we are after all raising s to a power. (The period is needed here as well.) » s.^2 ans = 1 64 25 The table below summarizes the operators that are available in MATLAB. + addition - subtraction * multiplication ^ power ' transpose \ left division / right division Remember that the multiplication, power and division operators can be used in conjunction with a period to specify an element-wise operation. Exercises Create a diary session called sec1 in which you should complete the following exercises. Define,

Page 15: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 15 of 83

A =

2 9 0 00 4 1 47 5 5 17 8 7 4

⎢ ⎢ ⎢ ⎢

⎥ ⎥ ⎥ ⎥

,

b =

−1609

⎢ ⎢ ⎢ ⎢

⎥ ⎥ ⎥ ⎥

,

a = 3 −2 4 −5[ ]

1. Calculate the following (when defined) (a)

A⋅ b (b)

a + 4 (c)

b⋅ a (d)

a⋅ bT (e)

A⋅ aT 2. Explain any differences between the answers that MATLAB gives when you type in A*A, A^2 and A.^2. 3. What is the command that isolates the submatrix that consists of the 2nd to 3rd rows of the matrix A? 4. Solve the linear system

A⋅ x = b for x. Check your answer by multiplication. Edit your text file to delete any errors (or typos) and hand in a readable printout. Built-in functions There are numerous built-in functions (i.e. commands) in MATLAB. We will mention a few of them in this section by separating them into categories. Scalar Functions Certain MATLAB functions are essentially used on scalars, but operate element-wise when applied to a matrix (or vector). They are summarized in the table below. sin trigonometric sine cos trigonometric cosine tan trigonometric tangent asin trigonometric inverse sine (arcsine) acos trigonometric inverse cosine (arccosine) atan trigonometric inverse tangent (arctangent) exp exponential log natural logarithm abs absolute value sqrt square root rem remainder round round towards nearest integer floor round towards negative infinity ceil round towards positive infinity Even though we will illustrate some of the above commands in what follows, it is strongly recommended to get help on all of them to find out exactly how they are used. The trigonometric functions take as input radians. Since MATLAB uses pi for the number π = 3.1415...

Page 16: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 16 of 83

» sin(pi/2) ans = 1 » cos(pi/2) ans = 6.1230e-017 The sine of π/2 is indeed 1 but we expected the cosine of π/2 to be 0. Well, remember that MATLAB is a numerical package and the answer we got (in scientific notation) is very close to 0 ( 6.1230e-017 = 6.1230 x 10–17 ≈ 0). Since the exp and log commands are straightforward to use, let us illustrate some of the other commands. The rem command gives the remainder of a division. So the remainder of 12 divided by 4 is 0 as shown; » rem(12,4) ans = 0 Likewise, the remainder of 12 divided by 5 is 2. » rem(12,5) ans = 2 The floor, ceil and round commands are illustrated below. » floor(1.4) ans = 1 » ceil(1.4) ans = 2 » round(1.4) ans = 1 Keep in mind that all of the above commands can be used on vectors with the operation taking place element-wise. For example, if x = [0, 0.1, 0.2, . . . , 0.9, 1], then y = exp(x) will produce another vector y, of the same length as x, whose entries are given by y = [eo, e0.1, e0.2, . . ., e1].

Page 17: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 17 of 83

» x = [0:0.1:1] x= Columns 1 through 7 0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 Columns 8 through 11 0.7000 0.8000 0.9000 1.0000 » y = exp(x) y = Columns 1 through 7 1.0000 1.1052 1.2214 1.3499 1.4918 1.6487 1.8221 Columns 8 through 11 2.0138 2.2255 2.4596 2.7183 This is extremely useful when plotting data. See Data Visualization in MATLAB ahead for more details on plotting. Also, note that MATLAB displayed the results as 1-by-11 matrices (i.e. row vectors of length 11). Since there was not enough space on one line for the vectors to be displayed, MATLAB reports the column numbers. Vector Functions Other MATLAB functions operate essentially on vectors returning a scalar value. Some of these functions are given in the table below. max largest component min smallest component length length of a vector sort sort in ascending order sum sum of elements prod product of elements median median value mean mean value std standard deviation Once again, it is strongly suggested to get help on all the above commands. Some are illustrated below. Let z be the following row vector. » z = [0.9347,0.3835,0.5194,0.8310]

Page 18: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 18 of 83

z = 0.9347 0.3835 0.5194 0.8310 Then » max(z) ans = 0.9347 » min(z) ans = 0.3835 » sort(z) ans = 0.3835 0.5194 0.8310 0.9347 » sum(z) ans = 2.6686 » mean(z) ans = 0.6671 The above (vector) commands can also be applied to a matrix. In this case, they act in a column- by-column fashion to produce a row vector containing the results of their application to each column. The example below illustrates the use of the above (vector) commands on matrices. Suppose we wanted to find the maximum element in the following matrix. » M=[ 0.7012,0.2625,0.3282 0.9103,0.0475,0.6326 0.7622,0.7361,0.7564]; If we used the max command on M, we will get the row in which the maximum element lies (remember the vector functions act on matrices in a column-by-column fashion). » max(M) ans = 0.9103 0.7361 0.7564 To isolate the largest element, we must use the max command on the above row vector. Taking advantage of the fact that MATLAB assigns the variable name ans to the answer we obtained, we can

Page 19: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 19 of 83

simply type » max(ans) ans = 0.9103 The two steps above can be combined into one in the following. » max(max(M)) ans = 0.9103 Combining MATLAB commands can be very useful when programming complex algorithms where we do not wish to see or access intermediate results. More on this and other programming features of MATLAB in Programming in MATLAB section ahead. Matrix Functions Much of MATLAB’s power comes from its matrix functions. These can be further separated into two sub-categories. The first one consists of convenient matrix building functions, some of which are given in the table below. eye identity matrix zeros matrix of zeros ones matrix of ones diag extract diagonal of a matrix or create diagonal matrices triu upper triangular part of a matrix tril lower triangular part of a matrix rand randomly generated matrix Make sure you ask for help on all the above commands. To create the identity matrix of size 4 (i.e. a square 4-by-4 matrix with ones on the main diagonal and zeros everywhere else) we use the command eye. » eye(4,4) ans = 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 The numbers in parenthesis indicates the size of the matrix. When creating square matrices, we can specify only one input referring to size of the matrix. For example, we could have obtained the above identity matrix by simply typing eye(4). The same is true for the matrix building functions below. Similarly, the command zeros creates a matrix of zeros and the command ones creates a matrix of ones.

Page 20: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 20 of 83

» zeros(2,3) ans = 0 0 0 0 0 0 » ones(2) ans = 1 1 1 1 We can create a randomly generated matrix using the rand command. (The entries will be uniformly distributed between 0 and 1.) » C = rand(5,4) C = 0.2190 0.3835 0.5297 0.4175 0.0470 0.5194 0.6711 0.6868 0.6789 0.8310 0.0077 0.5890 0.6793 0.0346 0.3834 0.9304 0.9347 0.0535 0.0668 0.8462 The commands triu and tril, extract the upper and lower part of a matrix, respectively. Let us try them on the matrix C defined above. » triu(C) ans = 0.2190 0.3835 0.5297 0.4175 0 0.5194 0.6711 0.6868 0 0 0.0077 0.5890 0 0 0 0.9304 0 0 0 0 » tril(C) ans = 0.2190 0 0 0 0.0470 0.5194 0 0 0.6789 0.8310 0.0077 0 0.6793 0.0346 0.3834 0.9304 0.9347 0.0535 0.0668 0.8462 Once the extraction took place, the “empty” positions in the new matrices are automatically filled with zeros. As mentioned earlier, the command diag has two uses. The first use is to extract a diagonal of a matrix,

Page 21: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 21 of 83

e.g. the main diagonal. Suppose D is the matrix given below. Then, diag(D) produces a column vector, whose components are the elements of D that lie on its main diagonal. » D=[ 0.9092 0.5045 0.9866 0.0606 0.5163 0.4940 0.9047,0.3190,0.2661]; » diag(D) ans = 0.9092 0.5163 0.2661 The second use is to create diagonal matrices. For example, » diag([0.9092;0.5163;0.2661]) ans = 0.9092 0 0 0 0.5163 0 0 0 0.2661 creates a diagonal matrix whose non-zero entries are specified by the vector given as input. (A short cut to the above construction is diag(diag(D))). This command is not restricted to the main diagonal of a matrix; it works on off diagonals as well. See help diag for more information. Let us now summarize some of the commands in the second sub-category of matrix functions. size size of a matrix det determinant of a square matrix inv inverse of a matrix rank rank of a matrix rref reduced row echelon form eig eigenvalues and eigenvectors poly characteristic polynomial norm norm of matrix (1-norm, 2-norm, n-norm) cond condition number in the 2-norm lu LU factorization qr QR factorization chol Cholesky decomposition svd singular value decomposition Don’t forget to get help on the above commands. To illustrate a few of them, define the following matrix. » A = [9,7,0;0,8,6;7,1,-6] A =

Page 22: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 22 of 83

9 7 0 0 8 6 7 1 -6 » size(A) ans = 33 » det(A) ans = -192 Since the determinant is not zero, the matrix is invertible. » inv(A) ans = 0.2812 -0.2187 -0.2187 -0.2187 0.2812 0.2812 0.2917 -0.2083 -0.3750 We can check our result by verifying that AA–1 = I and A–1A = I. » A*inv(A) ans = 1.0000 0.0000 0.0000 0.0000 1.0000 0.0000 0.0000 0.0000 1.0000 » inv(A)*A ans = 1.0000 0.0000 0.0000 0.0000 1.0000 0.0000 0.0000 0.0000 1.0000 Let us comment on why MATLAB uses both 0’s and 0.0000’s in the answer above. Recall that we are dealing with a numerical package that uses numerical algorithms to perform the operations we ask for. Hence, the use of floating point (vs. exact) arithmetic causes the “discrepancy” in the results. From a practical point of view, 0 and 0.0000 are the same. The eigenvalues and eigenvectors of A (i.e. the numbers

λ and vectors x that satisfy

A⋅ x = λ⋅ x ) can be obtained through the eig command. » eig(A) ans =

Page 23: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 23 of 83

12.6462 3.1594 -4.8055 produces a column vector with the eigenvalues and » [X,D]=eig(A) X= -0.8351 -0.6821 0.2103 -0.4350 0.5691 -0.4148 -0.3368 -0.4592 0.8853 D= 12.6462 0 0 0 3.1594 0 0 0 -4.8055 produces a diagonal matrix D with the eigenvalues on the main diagonal, and a full matrix X whose columns are the corresponding eigenvectors. Exercises Create a diary session called sec2 in which you should complete the following exercises using MATLAB commands. When applicable, use the matrix A and the vectors b and a, that were defined in the previous section’s exercises. 1. Construct a randomly generated 2-by-2 matrix of positive integers. 2. Find the maximum and minimum elements in the matrix A. 3. Sort the values of the vector b. 4. (a) Find the eigenvalues and eigenvectors of the matrix B = A–1. Store the eigenvalues in a column

vector you should name lambda. (b) With I the 4-by-4 identity matrix, calculate the determinant of the matrix B – lambdaj I , for j = 1, 2, 3, 4 (Note: lambda1 is the first eigenvalue, lambda2 is the second eigenvalue etc.).

Basic Plotting We end our discussion on the basic features of MATLAB by introducing the commands for data visualization (i.e. plotting). By typing help plot you can see the various capabilities of this main command for two-dimensional plotting, some of which will be illustrated below. If x and y are two vectors of the same length then plot(x,y) plots x versus y. For example, to obtain the graph of y = cos(x) from – π to π, we can first define the vector x with components equally spaced numbers between –π and π, with increment, say 0.01. » x = -pi:0.01:pi; We placed a semicolon at the end of the input line to avoid seeing the (long) output. Note that the smallest the increment, the “smoother” the curve will be. Next, we define the vector y

Page 24: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 24 of 83

» y = cos(x); (using a semicolon again) and we ask for the plot » plot(x,y) At this point a new window will open on our desktop in which the graph (as seen below) will appear.

It is good practice to label the axis on a graph and if applicable indicate what each axis represents. This can be done with the xlabel and ylabel commands. » xlabel('x') » ylabel('y=cos(x)') Inside parentheses, and enclosed within single quotes, we type the text that we wish to be displayed along the x and y axis, respectively. We could even put a title on top using » title('Graph of cosine from - \pi to \pi') as long as we remember to enclose the text in parentheses within single quotes. The back-slash ( \ ) in front of pi allows the user to take advantage of LaTeX commands. If you are not familiar with the mathematical typesetting software LaTeX (and its commands), ignore the present commend and simply type » title('Graph of cosine from -pi to pi') Both graphs are shown below. These commands can be invoked even after the plot window has been opened and MATLAB will make all the necessary adjustments to the display.

4 3 2 1 0 1 2 3 41

0.8

0.6

0.4

0.2

0

0.2

0.4

0.6

0.8

1

Page 25: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 25 of 83

Various line types, plot symbols and colors can be used. If these are not specified (as in the case above) MATLAB will assign (and cycle through) the default ones as given in the table below. y yellow . point m magenta o circle c cyan x x-mark r red + plus g green - solid b blue * star w white : dotted k black -. dashdot -- dashed So, to obtain the same graph but in green, we type » plot(x,y,’g’) where the third argument indicating the color, appears within single quotes. We could get a dashed line instead of a solid one by typing » plot(x,y,’--’) or even a combination of line type and color, say a blue dotted line by typing » plot(x,y,’b:’) Multiple curves can appear on the same graph. If for example we define another vector » z = sin(x); we can get both graphs on the same axis, distinguished by their line type, using » plot(x,y,'r--',x,z,'b:')

4 3 2 1 0 1 2 3 41

0.8

0.6

0.4

0.2

0

0.2

0.4

0.6

0.8

1

x

y=co

s(x)

Graph of cosine from to

Page 26: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 26 of 83

The resulting graph can be seen below, with the red dashed line representing y = cos(x) and the blue dotted line representing z = sin(x).

When multiple curves appear on the same axis, it is a good idea to create a legend to label and distinguish them. The command legend does exactly this. » legend('cos(x)','sin(x)') The text that appears within single quotes as input to this command, represents the legend labels. We must be consistent with the ordering of the two curves, so since in the plot command we asked for cosine to be plotted before sine, we must do the same here.

At any point during a MATLAB session, you can obtain a hard copy of the current plot by either issuing the command print at the MATLAB prompt, or by using the command menus on the plot window. In addition, MATLAB plots can by copied and pasted (as pictures) in your favorite word processor (such as Microsoft Word). This can be achieved using the Edit menu on the figure window.

4 3 2 1 0 1 2 3 41

0.8

0.6

0.4

0.2

0

0.2

0.4

0.6

0.8

1

4 3 2 1 0 1 2 3 41

0.8

0.6

0.4

0.2

0

0.2

0.4

0.6

0.8

1

cos(x)sin(x)

Page 27: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 27 of 83

Another nice feature that can be used in conjunction with plot is the command grid, which places grid lines to the current axis (just like you have on graphing paper). Type help grid for more information. Other commands for data visualization that exist in MATLAB include subplot create an array of (tiled) plots in the same window loglog plot using log-log scales semilogx plot using log scale on the x-axis semilogy plot using log scale on the y-axis surf 3-D shaded surface graph surfl 3-D shaded surface graph with lighting mesh 3-D mesh surface It is left to the reader to further investigate the above commands through MATLAB’s help command. We illustrate here how to obtain one of the surface pictures on the cover of this guide: >> [x,y] = meshgrid(-3:.1:3,-3:.1:3); >> z = 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2)... -10*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2)... -1/3*exp(-(x+1).^2 - y.^2); >> surf(z) >> xlabel('x') >> ylabel('y') >> zlabel('z') >> title('Peaks')

Type help meshgrid, help surf and help peaks for more information on the above surface.

020

4060

80

0

20

40

60

8010

5

0

5

10

x

Peaks

y

z

Page 28: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 28 of 83

PROGRAMMING IN MATLAB M-files: Scripts and functions To take advantage of MATLAB’s full capabilities, we need to know how to construct long (and sometimes complex) sequences of statements. This can be done by writing the commands in a file and calling it from within MATLAB. Such files are called “m-files” because they must have the filename extension “.m”. This extension is required in order for these files to be interpreted by MATLAB. There are two types of m-files: script files and function files. Script files contain a sequence of usual MATLAB commands, that are executed (in order) once the script is called within MATLAB. For example, if such a file has the name compute.m, then typing the command compute at the MATLAB prompt will cause the statements in that file to be executed. Script files can be very useful when entering data into a matrix. Function files, on the other hand, play the role of user defined commands that often have input and output. You can create your own commands for specific problems this way, which will have the same status as other MATLAB commands. Let us give a simple example. The text below is saved in a file called log3.m and it is used to calculate the base 3 logarithm of a positive number. The text file can be created in a variety of ways, for example using the built-in MATLAB editor through the command edit (that is available with MATLAB 5.0 and above), or your favorite (external) text editor (e.g. Notepad or Wordpad in Microsoft Windows). You must make sure that the filename has the extension “.m” ! function [a] = log3(x) % [a] = log3(x) - Calculates the base 3 logarithm of x. a = log(abs(x))./log(3); % End of function Using this function within MATLAB to compute log 3(5), we get » log3(5) ans = 1.4650 Let us explain a few things related to the syntax of a function file. Every MATLAB function begins with a header, which consists of the following : (a) the word function, (b) the output(s) in brackets, (the variable a in the above example) (c) the equal sign, (d) the name of the function, which must match the function filename (log3 in the above example) and (e) the input(s) (the variable x in the above example). Any statement that appears after a “%” sign on a line is ignored by MATLAB and plays the role of comments in the subroutine. Comments are essential when writing long functions or programs, for clarity. In addition, the first set of comments after the header in a function serve as on-line help. For example, see what happens when we type » help log3 [a] = log3(x) - Calculates the base 3 logarithm of x. MATLAB gave us as “help” on the function we defined, the text that we included after the header in the

Page 29: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 29 of 83

file. Finally, the algorithm used to calculate the base 3 logarithm of a given number, is based on the formula log 3(x) = ln(|x|) / ln(3). Since the logarithm of a negative number is undefined, we use the absolute value for “safety”. Also, note that we have allowed for a vector to be passed as input, by using element-wise division in the formula. During a MATLAB session, we may call a function just like we did in the above example, provided the file is saved in the current (working) directory. This is the reason why in the beginning of this guide we suggested that you should create a working directory and switch to that directory from within MATLAB. It should be noted that both types of m-files can reference other m-files, including themselves in a recursive way. Exercises Write a script m-file called rand_int.m that once called within MATLAB gives a random integer. Loops We will now cover some commands for creating loops, which are not only used in writing m- files, but in regular MATLAB sessions as well. The examples that we will give will include both situations. The two types of loops that we will discuss are “for” and “while” loops. Both loop structures in MATLAB start with a keyword such as for, or while and they end with the word end. The “for” loop allows us to repeat certain commands. If you want to repeat some action in a predetermined way, you can use the “for” loop. The “for” loop will loop around some statement, and you must tell MATLAB where to start and where to end. For example, >> for j=1:4 j+2 end j= 3 j= 4 j= 5 j= 6 looped through the numbers 1, ..., 4 and every time printed the current number plus 2. Enclosed between the for and end, you can have multiple statements just like in the example below. Here, we define the vector x = [1, 2, ... , 10] and we calculate x2 = [12, 22, ... , 102], which we name x2. The semicolon at the end of the inner statement in the loop suppresses the printing of unwanted intermediate results. » x = 1:10 x = 1 2 3 4 5 6 7 8 9 10 » for i=1:10

Page 30: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 30 of 83

x2(i) = x(i)^2; end » x2 x2 = 1 4 9 16 25 36 49 64 81 100 Even though for loops are convenient to use in certain cases, they are not always the most efficient way to perform an operation. In the above example, we would have been better off using » x2 = x.^2 x2 = 1 4 9 16 25 36 49 64 81 100 instead. There are occasions, however, where the “vectorized” notation of MATLAB cannot help us perform the operations we want, and loops are needed despite the fact that they are not as efficient. Nested loops can also be created. In the following example, we calculate the square of the entries in a matrix. (This again is not efficient but it is used for illustration purposes only.) » A = [1,5,-3;2,4,0;-1,6,9] A = 1 5 -3 2 4 0 -1 6 9 » for i=1:3 for j=1:3 A2(i,j) = A(i,j)^2; end end » A2 A2 = 1 25 9 4 16 0 1 36 81 For a more realistic example, consider the m-file gaussel.m, which performs Gaussian elimination (and back substitution) to solve the square system A x = b. function [x] = gaussel(A,b) % [x] = gaussel(A,b) % % This subroutine will perform Gaussian elimination and % and back substitution to solve the system Ax=b % INPUT: A – matrix for the left hand side.

Page 31: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 31 of 83

% b- vector for the right hand side. % % OUTPUT: x – the solution vector. N = max(size(A)); Perform Gaussian Elimination for j=2:N, for i=j:N, m = A(i,j-1)/A(j-1,j-1); A(i,:) = A(i,:) - A(j-1,:)*m; b(i) = b(i) - m*b(j-1); end end % Perform back substitution x = zeros(N,1); x(N) = b(N)/A(N,N); for j=N-1:-1:1, x(j) = (b(j)-A(j,j+1:N)*x(j+1:N))/A(j,j); end % End of function To illustrate the use of the above file, we define » A = [4 3 2 3;1 2 3 6;4 2 2 1;9 9 1 -2] A = 4 3 2 3 1 2 3 6 4 2 2 1 9 9 1 -2 » b = [1;0;2;-5] b = 1 0 2 -5 Since, the function does not check to see if the matrix A is invertible, we do so ourselves. » det(A) ans = -94

Page 32: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 32 of 83

The solution to A x = b is given by » x = gaussel(A,b) x = 1.2979 -1.7660 -0.0213 0.3830 Of course, a more efficient way to solve such a linear system would be through the built-in MATLAB solver. That is, we could have typed x = A\b to obtain the same answer. Try it! The second type of loop is the “while” loop. The “while” loop repeats a sequence of commands as long as some condition is met. For example, given a number n, the following m-file (exple.m) will display the smallest non-negative integer a such that 2a ≥ n. function [a] = exple(n)

% [a] = exple(n) % a = 0; while 2^a < n a = a + 1; end % End of function » a = exple(4) a = 2 The conditional statement in the “while” loop is what makes it differ from the “for” loop. In the above example we used the conditional statement

while 2^a < n which meant that MATLAB would check to see if this condition is met, and if so proceed with the statement that followed. Such conditional statements are also used in “if” statements that are discussed in the next section. To form a conditional statement we use relational operators. The following are available in MATLAB. < less than > greater than <= less than or equal >= greater than or equal == equal ~= not equal

Page 33: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 33 of 83

Note that “=” is used in assignments and “= =” is used in relations. Relations may be connected (or quantified) by the following logical operators. & and | or ~ not Exercises The n-by-n Hilbert matrix H, has as its entries Hi,j = 1/(i + j – 1), i,j = 1, 2, ..., n. Create a double “for loop” to generate the 5-by-5 Hilbert matrix and check your answer using the built-in MATLAB command hilb. If statement There are times when you would like your algorithm/code to make a decision, and the “if” statement is the way to do it. The general syntax in MATLAB is as follows : if relation statement(s) elseif relation % if applicable statement(s) % if applicable else % if applicable statement(s) % if applicable end The logical operators (&, |, ~) could also be used to create more complex relations. Let us illustrate the “if” statement through a simple example. Suppose we would like to define and plot the piecewise defined function

F =x 2 if −1 < x < 0.50.25 if 0.5 ≤ x <1

⎧ ⎨ ⎩

This is done with the use of the “if” statement in MATLAB as follows. First we define the “domain” vector x from –1 to 1 with increment 0.01 to produce a smooth enough curve. » x=-1:0.01:1; Next, we loop through the values of x and for each one we create the corresponding function value F as a vector. » for i=1:length(x) if x(i) < 0.5 F(i) = x(i)^2; else F(i) = 0.25; end end

Page 34: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 34 of 83

Finally, we plot the two vectors (using a solid black curve). » plot(x, F, ’-k’)

As a second example, we would like to write a subroutine that takes as input a square matrix and returns its inverse (if it exists). The m-file below (chk_inv.m) will perform this task for us, and make use of the “if” statement. If the matrix is not square or if it does not have an inverse, the subroutine should print a message letting us know and it will terminate without computing anything. We will also make use of comments within the m-file to make it more readable. function [Ainv] = chk_inv(A) % [Ainv] = chk_inv(A) % Calculate the inverse of a matrix A % if it exists. [m,n] = size(A); % compute the size of the matrix A if m~=n % check if A is square disp('Matrix is not square.'); break % quit the function elseif det(A)==0 % check if A is singular disp('Matrix is singular.'); break % quit the function else Ainv = inv(A); % compute the inverse end % End of function Here is a sample run of the above program with a random 3-by-3 matrix. » A = rand(3,3) A = 0.0475 0.6326 0.3653

1 0.8 0.6 0.4 0.2 0 0.2 0.4 0.6 0.8 10

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

Page 35: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 35 of 83

0.7361 0.7564 0.2470 0.3282 0.9910 0.9826 » chk_inv(A) ans = -2.4101 1.2551 0.5806 3.1053 0.3544 -1.2437 -2.3270 -0.7767 2.0783 It is left to the reader to see what answers other input matrices will produce. In the above m-file, we used two “new” commands: disp and break. As you can imagine, break simply causes the current operation to stop (exit the program in this case). The command disp takes as input text enclosed within single quotes and displays it on the screen. See help disp for more information of this and other text displaying commands. As a final example, let us write an m-file called fact.m that gives the factorial of a positive number n = 1 2 3 4 . . . (n – 1)n, using the recursive formula n! = n (n – 1). This example will not only illustrate the use of the “if” statement, but that of a recursive function as well. function [N] = fact(n) % [N] = fact(n) % Calculate n factorial if (n = = 1) | (n = = 0) N = 1; else N = fact(n-1); end % End of function Exercises 1. Modify the m-file log3.m from the previous section, by removing the absolute value within the logarithms (that was used for “safety”). Your function should now check to see if the input is negative or zero, print out a message saying so, and then terminate. If the input is positive then your function should proceed to calculate the logarithm base 3 of the input. 2. Write a function m-file called div5.m that takes as input a real number and checks to see if it is divisible by 5. An appropriate message indicating the result should be the output.

Page 36: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 36 of 83

DATA IMPORT AND EXPORT To obtain information regarding the supported data types see the list from MATLAB help. There you will also find information regarding specific functions available. Other data types most probably have to be read and written with low-level input/output functions. If you need to import complex data (in particular if you have to do it only once or few times), it is probably a good idea to try to use the graphical tool provided by the MATLAB environment; the Matlab Import Wizard. You might later want to store the data in MATLAB file format. To open the Matlab Import Wizard select “import data” from the “file” menu in the MATLAB window. Depending on the file format MATLAB will ask you to specify e.g. delimiters in text files, header formats, whether the output should be a structure or several variables, etc. If you want to stick with the file formats provided by other programs it is probably a better idea to use specialized functions (either provided by MATLAB or written by yourself) for data import and export. Here are some useful commands handling data:

• exist(‘filename.mat’,’file’) Returns 2 (!) if file exists in current directory (or in directory specified by path in name) and 0 if not

• whos –file filename.mat displays variables contained in file in command window • w=whos(‘ –file’,’filename.mat’) returns struct array with fields name, size, bytes, class of

variables contained in file • delete filename.ext deletes file on disk • copyfile(oldname, dirname) copy file oldname to directory • copyfile(oldname, newname) copy file oldname to newname • cd directory changes the current working directory • p=path writes the current Matlab search path to string variable p • path(path,‘newpath’) adds the directory ‘newpath’ to the MATLAB search path

MATLAB data MATLAB native files are known as ‘mat’ files. The regular way to save data with Matlab is to write the workspace content (or parts of it) to a .mat file. These are some of the characteristics of ‘mat’ files:

• Format: Matlab binary format, cannot be opened by other programs • Content: Variables from the workspace are saved with their names and content. • Platform compatibility: mat-files are not platform-independent, but are cross-platform

compatible. Variables saved on one platform can be opened on other MATLAB platforms without any special treatment.

• Version compatibility: The binary format used for saving data changed from MATLAB version 6 to version 7. Data saved with version 6 can be loaded into version 7 without additional treatment. If you want to save variables with MATLAB 7 and load them into MATLAB 6 you have to use the –v6 option for the save command (e.g save filename variable –v6).

Saving and loading with graphical interface When using the graphical interface to save data MATLAB will open a save dialog box to choose the location where to save the file. The .mat extension is automatically added to the file name you specify.

Page 37: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 37 of 83

• Save the entire workspace: a. File menu in MATLAB desktop -> Save As b. Save button in workspace browser

• Save selected variables:

a. Select variables in Workspace browser. To select multiple variables, use shift+click or ctrl+click. Then open the context menu with right click and choose Save As.

• Load:

a. Double click on a .mat or ASCII file in the current directory window b. Use the “import data” icon in the Workspace browser c. File menu in MATLAB desktop -> Import Data

Save command: The command to save workspace variables is “Save”. By default, data is saved as .mat file, but save can also write ASCII files. “Save” can be used in various ways:

• save saves workspace to matlab.mat • save filename saves workspace to filename.mat

(extension .mat is added by MATLAB if not specified, filename can contain path information)

• save filename var1 var2 saves specified variables to filename.mat • save filename options saves workspace to filename.mat with options. For a

list of options (including use of regular expressions, saving structure fields as separate variables, MATLAB version information...), please refer to the help page.

• save filename var1 var2 options Saves specified variables with options • save(‘filename’,’var1’,var2’,...) Most convenient way to save if you generate

filenames or variable names as strings. E.g. fn=’myfile’; save(fn,’M’)

Load command: The load command is used to load MATLAB variables or ASCII files into the workspace. Data contained in ASCII files will be stored in a variable with the same name as the file. If variables with the same names as the newly loaded already exist in the workspace they will be overwritten. load also comes in several flavors:

• load loads all variables saved in matlab.mat into workspace. • load filename loads all saved variables saved in filename.mat into workspace (extension

.mat is first assumed, if the file has a different extension, MATLAB will try to open it as ASCII file).

• load –ascii filename forces load to treat the file as ascii regardless of the extension. If the file is not numeric text, load will return an error.

• load –mat filename forces load to treat the file as mat-file, regardless of the extension. If the file is not in MATLAB binary format, load will return an error.

• load filename var1 var2 loads specified variables into workspace • load(‘filename’,’var1’,var2’) most convenient way to load with automatically generated file or variable

names. E.g. (for i=1:N … fn=sprintf(‘data%d’,i); load(fn) … end).

• s=load(‘filename’,’var1’,var2’) loads variables var1 and var2 into a structure variable s with fields var1 and var2. Good way to prevent overwriting of workspace variables.

Formatted text

Page 38: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 38 of 83

Load: The normal load command can read ASCII data into MATLAB, as long as the file is organized as a rectangular table of numbers, with each number in a row separated by a blank, comma, or tab character, and with an equal number of elements in each row. In this case, the numbers will be assigned to a variable with the name of the file name (if the filename starts with a digit, MATLAB will add a preceding X, all non-alpabetic characters will be replaced by underscores). You can use the option –ascii to force MATLAB to read a file as ASCII, but MATLAB will try to do so anyway if the file name does not have the ending .mat. Save: MATLAB will save the content of a variable in an ASCII-file if the save command is used with the option –ascii. Specialized functions to read formatted text:  

• dlmread reads numeric data from the ASCII-delimited file filename, using the specified delimiter. Use \t to specify a tab delimiter. M = dlmread(filename, delimiter).

• textread reads formatted text from file into several output variables. For format options see help [A,B,C,...] = textread('filename','format').

• textscan reads formatted text from file into cell array after fopen. For format options see help C = textscan(fid, 'format').

• fscanf reads data from file after fopen (see below). • fgetl reads text line-by-line after fopen, including terminator symbol (see below). • fgets reads text line-by-line after fopen, without terminator symbol (see below).

Graphics: MATLAB figures: MATLAB saves figures by default as MATLAB figures with the ending “.fig”. Unfortunately, many programs use the .fig postfix for different formats and (as far as I know) no other program can directly use MATLAB figures in a reasonable way. So you have to choose a different format if you want to use figures for different contexts. However, it makes sense to save .fig files of figures if you want to continue your work on a figure later. All properties of the figure will be stored and if only parts of a data set are plotted the full data set will still be available after saving and loading as .fig files. Exporting graphics from MATLAB figures: Possible either by selecting “Export” on the “File” menu of the figure window or by using the function “saveas”. Importing graphics to a matrix: Function “imread” can read multiple graphics formats (color or grayscale), including jpeg, tiff, gif, bmp, png, hdf, xwd. Standard: A = imread(filename, fmt) with text string fmt specifying the file format with its standard file extension (e.g. ʻgifʼ) returns array A. If the image is a gray scale picture, A is a MxN array, if it is a true color picture, A is a MxNx3 array (for rgb), if it is a tiff picture, A is a MxNx4 array (CMYK). Refer to help page for more information and options. Exporting graphics from a matrix: function imwrite can write multiple graphics formats. See help for usage, formats and format specific parameters. Information about a graphics file: info = imfinfo(filename) returns a structure, info, whose fields contain information about an image in a graphics file. See help for information contained in the structure. Sound: Microsoft WAVE .wav files:

Page 39: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 39 of 83

• wavread: Reads Microsoft WAVE .wav sound files. Standard: [y,Fs,nbits] =wavread(‘filename.wav’) returns y: sampled data, Fs: sample rate in Hz, nbits: number of bits per sample used to encode the data in the file. For more options please refer to the help page

• wavwrite: Writes Microsoft Wave .wav files. Standard. wavwrite(y,FS,nbits,’filename.wav’) with y:

sampled data, Fs: sample rate in Hz, nbits: number of bits used for encoding (standard is 16, values 8, 24, 32 also possible). Amplitude values outside the range [- 1,+1] are clipped prior to writing.

Video: Audio/Video Interleaved .avi file:

• aviread: mov = aviread(filename) reads the AVI movie filename into the MATLAB movie structure mov. If filename does not include an extension, then .avi is used. Use the movie function to view the movie mov. The movie structure has two fields, cdata and colormap.

• avifile: Creates AVI file (see help for usage) • movie2avi: Creates AVI file from MATLAB movie (see help for usage) • movie(M): Play recorded movie frames (see help for usage and options) • im2frame: f=im2frame(x,map) converts image x and colormap map into a movie frame • frame2im: [x,map]=frame2im(F) converts movie frame to image

Compatibility with Microsoft programs: Excel spreadsheet files:

• Read Excel spreadsheet files: use the function xlsread. Standard usage num=xlsread(‘filename.xls’) returns numeric data in double array num. Spreadsheet cells filled with text will be replaced by NaN. For more options please refer to the help page.

• Write Excel spreadsheet files: use the function xlswrite. Standard usage xlswrite(‘filename.xls’,M)

will write the content of Matrix or cell array M to the first worksheet in the xls file, starting at cell A1. For more options please refer to the help page.

• Test if a file is an Excel file: typ=xlsinfo(‘filename’) returns the string ‘Micorsoft Excel Spreadsheet’ if

the file specified by filename is an XLS file that can be read by the MATLAB xlsread function. Otherwise, typ is the empty string, (' '). For more options please refer to the help page.

Data files generated with word:

• Save the data as text file with .txt and try to read as ASCII, but in general: better use some other program.

Windows paintbrush pcx files:

• Can be read in with imread                    

Page 40: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 40 of 83

DATA VISUALIZATION IN MATLAB The plot function has different forms, depending on the input arguments. If y is a vector, plot(y) produces a piecewise linear graph of the elements of y versus the index of the elements of y. If you specify two vectors as arguments, plot(x,y) produces a graph of y versus x. For example, these statements use the colon operator to create a vector of x values ranging from zero to 2, compute the sine of these values, and plot the result. >>x = 0:pi/100:2*pi; >>y = sin(x); >>plot(x,y) Now label the axes and add a title. The characters \pi create the symbol π. >>xlabel('x = 0:2\pi') >>ylabel('Sine of x') >>title('Plot of the Sine Function','FontSize',12)

Multiple Data Sets in One Graph Multiple x-y pair arguments create multiple graphs with a single call to plot. MATLAB automatically cycles through a predefined (but user settable) list of colors to allow discrimination between each set of data. For example, these statements plot three related functions of x, each curve in a separate distinguishing color. >> x = 0:pi/100:2*pi; >> y2 = sin(x-.25); >> y3 = sin(x-.5); Based on excerpts from the MATLAB online help feature. >> plot(x,y,x,y2,x,y3) The legend command provides an easy way to identify the individual plots.

0 1 2 3 4 5 6 71

0.8

0.6

0.4

0.2

0

0.2

0.4

0.6

0.8

1

x = 0:2

Sine

of x

Plot of the Sine Function

Page 41: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 41 of 83

>> legend('sin(x)','sin(x-.25)','sin(x-.5)')

Plotting Lines and Markers If you specify a marker type but not a linestyle, MATLAB draws only the marker. You may also want to use fewer data points to plot the markers than you use to plot the lines. For example, >> x1 = 0:pi/100:2*pi; >> x2 = 0:pi/10:2*pi; >> plot(x1,sin(x1),'r:',x2,sin(x2),'r+')

This plot shows the data twice using a different number of points for the dotted line and marker plots.

0 1 2 3 4 5 6 71

0.8

0.6

0.4

0.2

0

0.2

0.4

0.6

0.8

1

sin(x)sin(x .25)sin(x .5)

0 1 2 3 4 5 6 71

0.8

0.6

0.4

0.2

0

0.2

0.4

0.6

0.8

1

Page 42: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 42 of 83

Imaginary and Complex Data When the arguments to plot are complex, the imaginary part is ignored except when plot is given a single complex argument. For this special case, the command is a shortcut for a plot of the real part versus the imaginary part. Therefore, plot(Z) where Z is a complex vector or matrix, is equivalent to plot(real(Z),imag(Z)) For example, >> t = 0:pi/10:2*pi; >> plot(exp(i*t),'-o') >> axis equal draws a 20-sided polygon with little circles at the vertices. The command, axis equal, makes the individual tick mark increments on the x- and y-axes the same length, which makes this plot more circular in appearance.

Adding Plots to an Existing Graph The hold command enables you to add plots to an existing graph. When you type hold on MATLAB does not replace the existing graph when you issue another plotting command; it adds the new data to the current graph, rescaling the axes if necessary. For example, >>t=-1:0.01:1; >>y=t.^2+2*t-1; >>plot(t,y) >>hold Current plot held >> w=cos(t); >> plot(t,w)

1 0.5 0 0.5 11

0.8

0.6

0.4

0.2

0

0.2

0.4

0.6

0.8

1

Page 43: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 43 of 83

The hold on command causes the color of the plot to match with the existing plot in the figure. Multiple Plots in One Figure The subplot command enables you to display multiple plots in the same window or print them on the same piece of paper. Typing subplot(m,n,p) partitions the figure window into an m-by-n matrix of small subplots and selects the pth subplot for the current plot. The plots are numbered accordingly; first the top row of the figure window, then the second row, and so on. For example, these statements plot graphs in four different sub regions of the figure window. >> t = -pi:2*pi/100:pi; >> f1=sin(t.^2); >> f2=(sin(t)).^2; >> f3=cos(t.^2); >> f4=(cos(t)).^2; >> subplot(2,2,1);plot(t,f1); >> title('sin(t^2)') >> subplot(2,2,2);plot(t,f2); >> title('sin(t)^2') >> subplot(2,2,3);plot(t,f3); >> title('cos(t^2)') >> subplot(2,2,4);plot(t,f4); >> title('cos(t)^2')

1 0.8 0.6 0.4 0.2 0 0.2 0.4 0.6 0.8 12

1.5

1

0.5

0

0.5

1

1.5

2

Page 44: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 44 of 83

Polar and logarithmic plots To obtain a plot in polar coordinates, we use the command polar. For example, to plot the function r = 3cos2(θ/2)+θ ,0 ≤ θ ≤ 2π, we type >> t=0:0.01:2*pi; >> r=3*cos(t/2).^2+t; >> polar(t,r)

Many science and engineering applications require plots in which one or both axes have a logarithmic scale. The commands for these are loglog, semilogy and semilogx. For example, >> x=0:.25:10; >> y=2*exp(-2*x); >> subplot(2,2,1) >> plot(x,y,'b') >> title('x vs y') >> subplot(2,2,2) >> loglog(x,y,'r')

5 0 51

0.5

0

0.5

1sin(t2)

5 0 50

0.2

0.4

0.6

0.8

1sin(t)2

5 0 51

0.5

0

0.5

1cos(t2)

5 0 50

0.2

0.4

0.6

0.8

1cos(t)2

2

4

6

8

10

30

210

60

240

90

270

120

300

150

330

180 0

Page 45: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 45 of 83

>> title('log(x) vs log(y)') >> subplot(2,2,3) >> semilogy(x,y,'k') >> title('x vs log(y)') >> subplot(2,2,4) >> semilogx(x,y,'c') >> title('log(x) vs y')

Controlling the Axes The axis command supports a number of options for setting the scaling, orientation, and aspect ratio of plots. You can also set these options interactively. Type help axis for more information. By default, MATLAB finds the maxima and minima of the data to choose the axis limits to span this range. The axis command enables you to specify your own limits: axis([xmin, xmax, ymin, ymax]), or for three-dimensional graphs, axis([xmin, xmax, ymin, ymax, zmin, zmax]) Use the command axis auto to re-enable MATLAB's automatic limit selection. axis also enables you to specify a number of predefined modes. For example, axis square makes the x-axes and y-axes the same length. axis equal makes the individual tickmark increments on the x- and y-axes the same length. axis auto normal returns the axis scaling to its default, automatic mode. You can use the axis command to make the axis visible or invisible. axis on makes the axis visible (this is the default) axis off makes the axis invisible

0 5 100

0.5

1

1.5

2x vs y

10 1 100 10110 10

10 5

100

105log(x) vs log(y)

0 5 1010 10

10 5

100

105x vs log(y)

10 1 100 1010

0.5

1

1.5log(x) vs y

Page 46: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 46 of 83

grid toggles grid lines on and off grid on turns the grid lines on and grid off turns them back off again. For example, >> x=-2:0.01:2; >> plot(x,exp(-x.^2),'r') >> grid on >> axis([-2 2 0 1.25])

Saving a Figure To save a figure, select Save from the File menu. To save it using a graphics format, such as JPEG, for use with other applications, select Export from the File menu. You can also save from the command line - use the saveas command, including any options to save the figure in a different format. Using Plot Editing Mode The MATLAB figure window supports a point-and-click style editing mode that you can use to customize the appearance of your graph. In plot editing mode, you can use a graphical user interface, called the Property Editor, to edit the properties of objects in the graph. The Property Editor provides access to many properties of the root, figure, axes, line, light, patch, image, surfaces rectangle, and text objects. For example, using the Property Editor, you can change the thickness of a line, add titles and axes labels, add lights, and perform many other plot editing tasks. Printing Graphics You can print a MATLAB figure directly on a printer connected to your computer or you can export the figure to one of the standard graphic file formats supported by MATLAB. There are two ways to print and export figures: Using the Print option under the File menu, and using the print command. Printing from the Menu – There are four menu options under the File menu that pertain to printing: The Page Setup option displays a dialog box that enables you to adjust characteristics of the figure on the printed page. The Print Setup option displays a dialog box that sets printing defaults, but does not actually print the figure. The Print Preview option enables you to view the figure the way it will look on the

2 1.5 1 0.5 0 0.5 1 1.5 20

0.2

0.4

0.6

0.8

1

1.2

Page 47: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 47 of 83

printed page. The Print option displays a dialog box that lets you select standard printing options and print the figure. Generally, use Print Preview to determine whether the printed output is what you want. If not, use the Page Setup dialog box to change the output settings. Select the Page Setup dialog box Help button to display information on how to set up the page. Exporting Figure to Graphics Files – The Export option under the File menu enables you to export the figure to a variety of standard graphics file formats (such as JPEF, EPS, etc.). Using the print Command – The print command provides more flexibility in the type of output sent to the printer and allows you to control printing from M-files. The result can be sent directly to your default printer or stored in a specified file. A wide variety of output formats, including TIFF, JPEG, and PostScript, is available. For example, this statement saves the contents of the current figure window as color Encapsulated Level 2 PostScript in the file called magicsquare.eps. It also includes a TIFF preview, which enables most word processors to display the picture. >> print -depsc2 -tiff magicsquare.eps To save the same figure as a TIFF file with a resolution of 200 dpi, use the command >> print -dtiff -r200 magicsquare.tiff If you type print on the command line, print MATLAB prints the current figure on your default printer.

MESH AND SURFACE PLOTS MATLAB defines a surface by the z-coordinates of points above a grid in the x-y plane, using straight lines to connect adjacent points. The mesh and surf plotting functions display surfaces in three dimensions. mesh produces wireframe surfaces that color only the lines connecting the defining points; surf displays both the connecting lines and the faces of the surface in color. Visualizing Functions of Two Variables To display a function of two variables, z = f (x,y): Generate X and Y matrices consisting of repeated rows and columns, respectively, over the domain of the function. Use X and Y to evaluate and graph the function. The meshgrid function transforms the domain specified by a single vector or two vectors x and y into matrices X and Y for use in evaluating functions of two variables. The rows of X are copies of the vector x and the columns of Y are copies of the vector y. The next example evaluates and graphs the two-dimensional sin function, sin(r)/r, between the x and y directions. R is the distance from the origin, which is at the center of the matrix. >> [X,Y] = meshgrid(-8:.5:8); >> R = sqrt(X.^2 + Y.^2); >> Z = sin(R)./R; >> mesh(X,Y,Z,'EdgeColor','black')

Page 48: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 48 of 83

SPECIALIZED GRAPHICS MATLAB supports a variety of graph types that enable you to present information effectively. The type of graph you select depends, to a large extent, on the nature of your data. The following list can help you select the appropriate graph: • Bar and area graphs are useful to view results over time, comparing results, and displaying individual contribution to a total amount. • Pie charts show individual contribution to a total amount. • Histograms show the distribution of data values. • Stem and stair-step plots display discrete data. • Compass, feather, and quiver plots display direction and velocity vectors. • Contour plots show equi-valued regions in data. Bar and area graphs Bar and area graphs display vector or matrix data. These types of graphs are useful for viewing results over a period of time, comparing results from different datasets, and showing how individual elements contribute to an aggregate amount. Bar graphs are suitable for displaying discrete data, whereas area graphs are more suitable for displaying continuous data. bar: Displays columns of m-by-n matrix as m groups of n vertical bars barh: Displays columns of m-by-n matrix as m groups of n horizontal bars bar3: Displays columns of m-by-n matrix as m groups of n vertical 3-D bars bar3h: Displays columns of m-by-n matrix as m groups of n horizontal 3-D bars area: Displays vector data as stacked area plots For example, >> x = -2.9:0.2:2.9; >> bar(x,exp(-x.^2)) >> colormap cool

105

05

10

10

5

0

5

100.4

0.2

0

0.2

0.4

0.6

0.8

1

Page 49: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 49 of 83

Pie charts display the percentage that each element in a vector or matrix contributes to the sum of all elements. pie and pie3 create 2-D and 3-D pie charts. Here is an example using the pie function to visualize the contribution that three products make to total sales. Given a matrix X where each column of X contains yearly sales figures for a specific product over a five-year period, >>X = [19.3 22.1 51.6; 34.2 70.3 82.4; 61.4 82.9 90.8; 50.5 54.9 59.1; 29.4 36.3 47.0]; Sum each row in X to calculate total sales for each product over the five-year period. >> x = sum(X); >> pie(x) >> colormap summer

Area graphs are useful for showing how elements in a vector or matrix contribute to the sum of all elements at a particular x location. By default, area accumulates all values from each row in a matrix and

3 2 1 0 1 2 30

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

25%

34%

42%

Page 50: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 50 of 83

creates a curve from those values. Using this matrix, >> Y = [5 1 2; 8 3 7; 9 6 8; 5 5 5; 4 2 3]; the statement, >> area(Y)

displays a graph containing three area graphs, one per column. The height of the area graph is the sum of the elements in each row. Each successive curve uses the preceding curve as its base. Histograms MATLAB's histogram functions show the distribution of data values. The functions that create histograms are hist and rose. hist: Displays data in a Cartesian coordinate system rose: Displays data in a polar coordinate system. The histogram functions count the number of elements within a range and display each range as a rectangular bin. The height (or length when using rose) of the bins represents the number of values that fall within each range. For example, >> yn = randn(10000,1); >> hist(yn) >> grid

1 1.5 2 2.5 3 3.5 4 4.5 50

5

10

15

20

25

Page 51: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 51 of 83

Discrete Data Graphs MATLAB has a number of specialized functions that are appropriate for displaying discrete data. This section describes how to use stem plots and stairstep plots to display this type of data. (Bar charts, discussed earlier, are also suitable for displaying discrete data.) stem: Displays a discrete sequence of y-data as stems from x-axis stem3: Displays a discrete sequence of z-data as stems from xy-plane stairs: Displays a discrete sequence of y-data as steps from x-axis For example, >> alpha = .02; beta = .5; t = 0:4:200; >> y = exp(-alpha*t).*sin(beta*t); >> stem(t,y,'k')

To see how the actual function graph "comes into play", look at: >> T=0:.1:200;

4 3 2 1 0 1 2 3 4 50

500

1000

1500

2000

2500

3000

0 20 40 60 80 100 120 140 160 180 2000.8

0.6

0.4

0.2

0

0.2

0.4

0.6

0.8

1

Page 52: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 52 of 83

>> hold >> Y = exp(-alpha*T).*sin(beta*T); >> plot(T,Y,'r')

Contour Plots The contour functions create, display, and label isolines determined by one or more matrices. clabel: Generates labels using the contour matrix and displays the labels in the current figure. contour: Displays 2-D isolines generated from values given by a matrix Z. contour3: Displays 3-D isolines generated from values given by a matrix Z. contourf: Displays a 2-D contour plot and fills the area between the isolines with a solid color. contourc: Low-level function to calculate the contour matrix used by the other contour functions. Two other functions also create contours. meshc: Displays a contour in addition to a mesh. surfc Displays a contour in addition to a surface. For example, consider the function z = x exp(–x2 – y2): >> [X,Y] = meshgrid(-2:.2:2,-2:.2:3); >> Z = X.*exp(-X.^2-Y.^2); >> surf(X,Y,Z) >> title('Z=X*e^{(X^2-Y^2)}')

0 20 40 60 80 100 120 140 160 180 2001

0.8

0.6

0.4

0.2

0

0.2

0.4

0.6

0.8

1

Page 53: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 53 of 83

The contour plot is given by: >> [C,f]=contourf(Z); >>clabel(C,f); >>colorbar

A combination of the two is given by >> surfc(x,y,z)

21

01

2

21

01

23

0.5

0

0.5

z=x e(x2 y2)

0

00

0.1

0.1

0.1

0.1

0.1

0.1

0.1

0.1

0.2

0.2

0.2

0.2

0.2

0.2

0.3

0.30.3 0.30.4 0.

4

5 10 15 20

5

10

15

20

25

0.4

0.3

0.2

0.1

0

0.1

0.2

0.3

0.4

Page 54: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 54 of 83

ADVANCED TOPICS Images Two-dimensional arrays can be displayed as images, where the array elements determine brightness or color of the images. For example, the statements >>load durer >>whos Name Size Bytes Class X 648x509 2638656 double array caption 2x28 112 char array map 128x3 3072 double array loads the (built-in data) file durer.mat, adding three variables to the workspace. The matrix X is a 648-by-509 matrix and map is a 128-by-3 matrix that is the colormap for this image. Note MAT-files, such as durer.mat, are binary files that can be created on one platform and later read by MATLAB on a different platform. The elements of X are integers between 1 and 128, which serve as indices into the colormap, map. >> image(X) >> colormap(map) >> axis image

21

01

2

21

01

23

0.5

0

0.5

Page 55: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 55 of 83

reproduces the Dürer's etching. A high resolution scan of the magic square in the upper right corner is available in another file, called detail.mat. Type >> load detail and then use the up-arrow key on your keyboard to re-execute the image, colormap, and axis commands. The statement >> colormap(hot)

adds some twentieth century colorization to the sixteenth century etching. The function hot generates a colormap containing shades of reds, oranges, and yellows. Typically a given image matrix has a specific colormap associated with it. Type help colormap for more information.

100 200 300 400 500

100

200

300

400

500

600

50 100 150 200 250 300 350

50

100

150

200

250

300

350

Page 56: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 56 of 83

Animations MATLAB provides two ways of generating moving, animated graphics. One is by continually erasing and then redrawing the objects on the screen, making incremental changes with each redraw. (You can save a number of different pictures and then play them back as a movie.) Here is an example showing simulated Brownian motion. Specify a number of points, such as >> n = 20 and a temperature or velocity, such as >> s = .02 The best values for these two parameters depend upon the speed of your computer. Generate n random points with (x, y) coordinates between –1/2 and +1/2. >>x = rand(n,1)-0.5; >>y = rand(n,1)-0.5; Plot the points in a square with sides at –1 and +1. Save the handle for the vector of points and set its EraseMode to xor. This tells the MATLAB graphics system not to redraw the entire plot when the coordinates of one point are changed, but to restore the background color in the vicinity of the point using an "exclusive or" operation. >> h = plot(x,y,'.'); >> axis([-1 1 -1 1]) >> axis square >> grid off >> set(h,'EraseMode','xor','MarkerSize',18) Now begin the animation. Here is an infinite while-loop, which you can eventually exit by typing Ctrl+c. Each time through the loop, add a small amount of normally distributed random noise to the coordinates of the points. Then, instead of creating an entirely new plot, simply change the XData and YData properties of the original plot. >> while 1 drawnow x = x + s*randn(n,1); y = y + s*randn(n,1); set(h,'XData',x,'YData',y) end Creating Movies If you increase the number of points in the Brownian motion example to something like n = 300 and s = .02, the motion is no longer very fluid; it takes too much time to draw each time step. It becomes more effective to save a predetermined number of frames as bitmaps and to play them back as a movie. First, decide on the number of frames, say >> nframes = 50; Next, set up the first plot as before, except using the default EraseMode (normal). >> x = rand(n,1)-0.5;

Page 57: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 57 of 83

>> y = rand(n,1)-0.5; >> h = plot(x,y,'.'); >> set(h,'MarkerSize',18); >> axis([-1 1 -1 1]) >> axis square >> grid off Generate the movie and use getframe to capture each frame. >> for k = 1:nframes x = x + s*randn(n,1); y = y + s*randn(n,1); set(h,'XData',x,'YData',y) M(k) = getframe; end Finally, play the movie 30 times. >> movie(M,30) We have only touched the surface here. For more information on ALL of MATLAB's graphics capabilities see the help menu in the MATLAB window.

Page 58: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 58 of 83

ADDITIONAL TOPICS Polynomials in MATLAB Even though MATLAB is a numerical package, it has capabilities for handling polynomials. In MATLAB, a polynomial is represented by a vector containing its coefficients in descending order. For instance, the following polynomial

p(x) = x2 –3x+5 is represented by the vector p = [1, -3, 5] and the polynomial

q(x) = x4 +7x2 –x

is represented by q = [1, 0, 7, -1, 0]. MATLAB can interpret any vector of length n + 1 as an nth order polynomial. Thus, if your polynomial is missing any coefficients, you must enter zeros in the appropriate place(s) in the vector, as done above. You can find the value of a polynomial using the polyval command. For example, to find the value of the polynomial q above at x = –1, you type » polyval(q,-1) ans = 7 Finding the roots of a polynomial is as easy as entering the following command. » roots(q) ans = 0 0.0712 + 2.6486i 0.0712 - 2.6486i -0.1424 Note that MATLAB can handle complex numbers as well, with i=sqrt(-1). This is reflected in the four roots above, two of which are complex. Suppose you want to multiply two polynomials together. Their product is found by taking the convolution of their coefficients. MATLAB’s command conv will do this for you. For example, if s(x) = x+2 and t(x) = x2 +4x+8, then

z(x) = s(x) t(x) = x3 +6x2 +16x+16 In MATLAB, we type » s = [1 2]; » t = [1 4 8]; » z = conv(s,t)

Page 59: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 59 of 83

z = 1 6 16 16 Dividing two polynomials is just as easy. The deconv function will return the remainder as well as the result. Let’s divide z by t and see if we get s. » [s,r] = deconv(z,t) s = 1 2 r = 0 0 0 0 As you can see, we get (as expected) the polynomial/vector s from before. If s did not divide z exactly, the remainder vector, r would have been something other than zero. MATLAB can obtain derivatives of polynomials very easily. The command polyder takes as input the coefficient vector of a polynomial and returns the vector of coefficients for its derivative. For example, with p(x) = x2 –3x + 5, as before » polyder(p) ans =

2 -3 What do you think (in terms of Calculus) the combination of commands polyval(polyder(p),1)would give? How about roots(polyder(p))? Exercises 1. Write a function m-file called polyadd.m that adds two polynomials (of not necessarily the same degree). The input should be the two vectors of coefficients and the output should be a new vector of coefficients representing their sum. 2. Find the maxima and minima (if any) of the polynomial function f(x) = x3 – x2 –3x. Plot the function and the maxima and minima (if any) using a ‘o’ for each minimum and a ‘*’ for each maximum. Numerical Methods In this section we mention some useful commands that are used in approximating various quantities of interest. We already saw that MATLAB can find the roots of a polynomial. Suppose we are interested in finding the root(s) of a general non-linear function. This can be done in MATLAB through the command fzero, which is used to approximate the root of a function of one variable, given an initial guess. We must first create an m-file that describes the function we are interested in, and then invoke the fzero command with the name of that function and an initial guess as input. Consider finding the root(s) of f(x) = ex – x2. We create the m-file called eff.m as seen below. function [F] = eff(x)

Page 60: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 60 of 83

% [F] = eff(x) F = exp(x) - x.^2; % End of function A plot of the function can prove to be very useful when choosing a good initial guess, since it gives as an idea as to where the root(s) lie. » x=-3:.01:3; plot(x,eff(x)); grid

We see from the above plot that there is one root between x = – 1 and x = 0. Hence, we choose as an initial guess – 0.5 and we type » fzero('eff',-0.5) ans = -0.7035 Note that the name of the function appears within single quotes as input to the function fzero. In addition, don’t forget that this is a four-digit approximation to the root. This is seen from » eff(-0.7035) ans = -6.1957e-005 which is not (quite) zero. Of course, the number of digits beyond the decimal point that are passed as input play an important role. See what happens when we change the format. » format long » fzero('eff',-0.5)

3 2 1 0 1 2 310

5

0

5

10

15

Page 61: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 61 of 83

ans = -0.70346742249839 » eff(-0.70346742249839) % eff(ans) also works ans = 0 As expected, a more accurate approximation gave much better results. When a function has more than one root, the value of the initial guess can be changed in order to obtain approximations to additional roots. Another useful command is fmin, which works in a similar way as the fzero command, but finds the minimum of a function. The command fmin requires as input the name of the function (within single quotes) and an interval over which the minimization will take place. For example, the MATLAB demo function g(x) = 1/((x–0.3)2 +0.01)+1/((x–0.9)2 +0.04)–6 is (already) in a file called humps.m. We see that there is a minimum between x = 0.5 and x = 1. So we type, » fmin('humps',0.5,1) ans = 0.63701067459059 to get the minimum x value. The minimum value of g is obtained by » humps(ans) ans = 11.25275412656430 When multiple minima are present, the endpoints of the interval given as input can be changed in order to obtain the rest of the minima. How do you think you can find the maximum of a function instead of the minimum? As a final command in this section, we mention quad, which approximates the value of a definite integral. Once again, the function we wish to integrate must be saved in a file and the name, along with the limits of integration, must be passed as input to the command quad. Consider integrating f(x) = ex – x2 over the interval x = 0 to 1. Since we already have this function in the file eff.m, we simply type » quad('eff',0,1) ans = 1.38495082136656

Page 62: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 62 of 83

How about the integral of sin(x) over 0 to

π . We know the answer in this case, and it should be 2. MATLAB knows the function sin, so without creating an m-file for it, we type » quad('sin',0,pi) ans = 2.00001659104794 The answer we got is close to 2 since after all it is only an approximation. We can get a closer approximation if we use the command quad8 instead. » quad8('sin',0,pi) ans = 1.99999999999989 The command quad8 uses a more accurate technique than that used in quad, hence the better approximation. An even “closer” approximation can be obtained if we pass as input to the command the tolerance we wish to have, i.e. the acceptable error in the approximation. For example, if we wish the error to be less than 10–10, we type » quad8('sin',0,pi,1e-10) ans = 2 and we get the answer exactly. The tolerance was passed in scientific notation above as the fourth input value.

Page 63: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 63 of 83

3. - CASE STUDY 1: The Modeling Process, Proportionality, and Geometric Similarity

In mathematical modeling we estimate the slope of proportionality line using the two-point method. Given (x1,y1) and (x2,y2) then the slope, k, is

.

We will use the following to illustrate the use of mathematical modeling and computational methods.

Proportionality/Geometric Similarity Modeling 1. PURPOSE: To provide an opportunity to develop proportionality arguments and test them using Computational Methods. 2. OBJECTIVE: Determine if the hearts of mammals are geometrically similar using your knowledge of proportionality models and technology. Provide a summary of your analysis using the following data to support or refute your argument. Heart Weight Length of cavity of Animal (in grams) left ventricle (in) Mouse 0.13 0.55 Rat 0.64 1.00 Rabbit 5.80 2.20 Dog 102.00 4.00 Sheep 210.00 6.50 Ox 2030.00 2.00 Horse 3900.00 16.00 3. PROCEDURE: a. Develop the proportionality model relating heart weight (HW) to the length (L) of the cavity of the left ventricle. You should get HW ∝ L3. b. Test the proportionality model using the data provided. Testing a proportionality model often involves the following steps: (1) Enter the raw observed data into your computer. (2) Plot the raw data to check for smoothness and potential "outliers", and to give you a "feel" of the type of proportionality you might find. (3) Make any necessary transformations to the data to properly fit the model. (4) Plot the transformed data to test the proportionality. It must form a straight line through the origin.

Page 64: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 64 of 83

(5) Estimate the constant of proportionality (use slope =rise/run to find the constant or use MATLAB’s linear fit). (6) Obtain an overlay of the actual vs. computed data or find the errors (yactual-ypredicted) to see if your model properly captures the trend of the data. Comment about the fit. A. Enter the raw data as Xdata and Ydata B. Enter the transformation to X or Y as needed C. Give the point to use in the slope D. Interpret the output. Heart Weight Length of cavity of Animal (in grams) left ventricle (in) Mouse 0.13 0.55 Rat 0.64 1.00 Rabbit 5.80 2.20 Dog 102.00 4.00 Sheep 210.00 6.50 Ox 2030.00 12.00 Horse 3900.00 16.00 >> weight=[0.13, 0.64, 5.8, 102, 210, 2030, 3900]; >> length=[.55, 1, 2.2, 4, 6.5, 12, 16]; >> plot(length,weight,'O')

What model can you fit through this data? Try a few different relationships such as HW ∝ L2. How does the data fit that model? Try the relationship HW ∝ L3 and see what the result is. >> length^1.5 = [.55^1.5,1^1.5,2.2^1.5,4^1.5,6.5^1.5,12^1.5,16^1.5];

>> length^2 = [.55^2,1^2,2.2^2,4^2,6.5^2,12^2,16^2]; >> length^3 = [.55^3,1^3,2.2^3,4^3,6.5^3,12^3,16^3]; >> slope = weight(7)/length(7) You can also perform a linear fit through the data using the following Matlab strategy. fit = polyfit(weight,length,1); The variable ‘fit’ is a 2 x 1 array that contains the slope and the y-intercept of the fit through the data. To extract the slope simply type in fit(1,1) in the command window.

Page 65: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 65 of 83

For example if we use W=0.9521*L3 as our equation for the model we obtain the following graph.

Finding the errors: In order to find the error we can use the least-squares method. This will find an error based on the difference between the model and the actual data. Using this error method we can do a minimization of the error in order to find the model parameters that will result in the smallest error. In MATLAB this can be achieved using the fminsearch function.

Page 66: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 66 of 83

4. - Case Study #2 – Basic Bioinformatics In bioinformatics it is often required to process large amounts of data in the form of text files that contain DNA or RNA sequences or the order in which amino acids appear in a certain protein of interest. MATLAB can be helpful in processing this data. Many of the built-in functions of MATLAB simplify the implementation of this type of processes by allowing the user to import data via the “Import Data” function. Additionally, MATLAB has recently released a Bioinformatics toolbox, which contains many useful functions for processing many different types of biological data. This toolbox is included in the latest version of MATLAB that is distributed to students and faculty by the SDSU College of Sciences. In this exercise you will import and process a DNA sequence to obtain various properties. Import the text file called “sequence” into your desktop by following your instructor’s instructions. Next construct a MATLAB script that is capable of opening the text file within the desktop and access the genetic sequence contained within the file. Process the genetic sequence to answer the following questions. 1. What is the total number of nucleotides in the sequence? 2. What is the total number of codons in the sequence? 3. How many A’s, C’s, G’s and T’s are there in the sequence? Calculate the percentage distribution of each of the nucleotides in the sequence? Which nucleotide has the highest presence? Which has the lowest presence? 4. The TATA box (also known as the Goldberg-Hogness box) is a DNA sequence commonly found in the promoter region of genes in archaea and eukaryotes. The TATA box is considered to be the core promoter sequence and it is the binding site of either general transcription factors or histones and is involved in the process of transcription by RNA polymerase. Due to its relevant function it is important to identify the TATA within a genetic sequence. Develop a subsection within the MATLAB script that loops through the entire genetic sequence and obtains the total number of TATA boxes within the sequence and the location(s). Store the number of TATA boxes in the variable No_TATA and the location of each of the TATA boxes detected under the variable Loc_TATA. 5. Partition the original genetic sequence into different segments based on the location of the TATA boxes detected. Store each of the different sections of the sequence under Gene_1, Gene_2, Gene_3, etc. What other manipulations can be done on the genetic sequence that would be of biological interest? Can you think of any data manipulations that would be useful in identifying current or emerging diseases?

Page 67: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 67 of 83

5. - Case Study #3 – A Measles Model This exercise is adapted from M.S. Barlett (1972). Can we construct a simple model of the spread of epidemics? We take as our example measles, a prevalent childhood disease before vaccinations became available. The incubation time is ½ week. During this time a child seems normal but is able to infect others. After this time the child is isolated until recovery, at which point he or she is immune. Roughly speaking measles outbreaks have been more severe during alternate years. Construct a simple differential equation model allowing for three categories: susceptible, infective, and isolated/recovered. Allow for an influx of new susceptible individuals due to births. Assume an infective makes contact with members of the population at random and infect a contacted susceptible with probability p. Construct a simple difference equation model. In the next steps use the differential equation model, the difference equation model, or both. Show that your model has some sort of cyclic behavior. If it does not, fix it, because measles outbreaks definitely tend to occur in a cyclic pattern. Estimate the parameters in your model to fit the ½ week incubation and 2-year cycle observations. Do the parameter values appear realistic? Measles outbreaks are seasonal (60% below average in summer and 60% above average in winter), but if you’ve constructed a model of the sort I expected, a slight change in the parameters in the previous task will cause the period to differ slightly from 2 years and so the peak will drift from season to season. What can be done? Most children make contact with more children during the school year than during vacation. Use this to fix up the model by introducing a seasonal variation in p. How much variation is required? Does this amount seem reasonable? Can you allow for contact between school districts? How much faith do you have in the model? What are its faults? Can you suggest improvements? The following data from Barlett’s article may be useful.

Annual Measles Deaths in London (1647-1660) Year 1647 1648 1649 1650 1651 1652 1653 1654 1655 1566 1567 1568 1569 1570

Annual Deaths

5 92 3 33 33 62 8 52 11 153 15 80 6 74

Mean Time Between Epidemics for Some Towns in England and Wales (1940-1956)

Population (thousands)

Time Between Outbreaks (weeks)

1046 73 658 106 415 92 269 93 180 94 113 80 66 74 22 86 18 92 12 79 11 98 7 199 4 105

Page 68: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 68 of 83

6. - Case Study #4 - Exploring the SIR Model Using pplane8  

Goal: Model a disease and investigate its spread under various conditions. Use graphs generated by pplane8 (and its many options) to estimate various quantities. Required Tools: Matlab and pplane8 (Google it and download it from Rice.edu) The SIR Model - The SIR model is a mathematical model of the spread of an infectious disease satisfying the following assumptions:

(i) the disease is short lived and not fatal (ii) the disease is spread by contact between individuals (an infected and an uninfected) (iii) individuals who recover develop immunity.

If S(t), I(t) and R(t) represent the number of Susceptible, Infected and Recovered individuals in a population, then under the assumptions above, the system of equations modeling the disease is given by the system:

dSdt

= −aSI

dIdt

= aSI − bI

dRdt

= bI

⎪ ⎪ ⎪ ⎪

⎪ ⎪ ⎪ ⎪

(Eq. I)

where a and b are positive constants (rates). Because the total population N remains constant (at least in the short term), for small values of t, we have

N = S(t) + I(t) + R(t) (Eq. II)

If we know S(t) and I(t), we also know R(t). Hence the 3rd equation in (Eq. I) is not necessary and since the system is also autonomous of population R, pplane8 can be used. Assignment – Throughout we shall assume that the total population is N = 1000, t is measured in months, and 0 < t < 4. Complete the following steps. (1) It was determined that a strain of flu spreading through Southern California satisfies the SIR model with a = 0.01 and b = 1.0. Initially 10 individuals are infected and 990 individuals of the population do not have nor have ever had this particular flu virus. Therefore 99% of the population is susceptible to the disease.

(a) Use pplane8 to plot the phase portrait (in the SI-plane) with the values of a and b and the initial conditions as above (use the options “Keyboard Input” and “Specify a computation interval”). Print your plot. Describe in words what is happening to S and I as time, t, progresses from 0 to 4 months.

Page 69: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 69 of 83

(b) From your graphs and the various graphing options in pplane8, approximate the maximum number of infected people during the first 4 months. Estimate when this occurs. (You may adjust your “Specific a computation interval” to get better estimates.) Change your graph settings by going to Edit -> Figure Properties menu and edit the x and y-axis to locate maxima and minima as needed.

(c) Is the number of susceptible individuals ever the same as the number of infected when 0 < t < 4?

If so, estimate when this occurs. Print your graph for both S and I on a single plot. (d) Estimate S(0.5), I(0.5), and I(1.5). These values will be used later.

(2) From section 1-(d), you estimated S(0.5), I(0.5), and I(1.5). Suppose that at t = 0.5 the flu virus mutates so that the value of a changes to a = 0.005 (b remains the same, b = 1.0). Estimate I, the number of infected, 1 month after the virus mutates. Compare this to the value of I(1.5) from above. Explain the difference. (3) Local officials will consider various strains of flu an epidemic when the number of infected individuals reaches a maximum. Using the model (Eq. I) in pplane8, with the values shown in the tables below, estimate the values of S at the time t* when the number of infected is a maximum (don’t submit plots):

With a = 0.015 and b = 1.0 With a = 0.02 and b = 1.0 S(0) I(0) S(t*) S(0) I(0) S(t*) 990 10 990 10 900 100 900 100 800 200 800 200 400 600 400 600

For the system (Eq. I), explain why you should expect that I(t) reaches a maximum when S(t*)=b/a. Do the results in your tables provide numerical evidence of the above statement? (4) It is sometimes of interest to rescale or normalize the quantities S, I, R in the model. If N is the total population, let

s'= SN

i'= IN

r'= RN,

which represents the fraction of total population which are susceptible, infected and recovered, respectively. What is s’ + i’ + r’?

(a) Using (Eq. I), derive the corresponding system for the new variables S, I, R. (b) An “unnamed source” in the local government made several statements to the press (shown

below) concerning the strain of flu modeled by (Eq. I), with a = 0.01, b = 1.0, and N = 100%. Your job is to use pplane8 to determine whether these statements are accurate.

Statement #1: If initially half the population is susceptible but only 10% of the population is

infected, then there will never be more than 15% of the population infected. Statement #2: If initially 25% of the population is infected and 25% is susceptible, then the

number of susceptible individuals is never again the same as the number of infected.

Page 70: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 70 of 83

Statement #3: If initially there are no individuals with immunity and the number of susceptible

and infected is the same, then after 1 month at least 50% of the population will be in the recovered group.

Print the graphs to help support your claims about the statements. (5) Complete the following

Using the system (Eq. I), show that

dSdI

=aSI

bI − aSI.

Page 71: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 71 of 83

7. - Case Study #5 – Building an SIR System of Differential Equations

How can I use Differential Equations to Build a Model? In applying differential equations to any of the numerous fields in which they are useful, it is first necessary to formulate the appropriate differential equation that describes, or models the problem being investigated. For example, in our flu scenario we would like to know the infection and recovery rates to properly establish the set of equations. It is also useful to know the mode of transmission of the disease and whether or not the recovered individuals will become immune to the flu or will regain susceptibility. At this point the data can be imported directly from your graphical representation and from your calculations or approximations of the initial parameters based on historical data. In constructing mathematical models yourself, you should recognize that each problem is different, and that successful modeling is not a skill that can be reduced to the observance of a set of prescribed rules. There is no cookbook recipe for constructing an accurate model since modeling is as much an art as it is a science and constructing a satisfactory model is sometimes the most difficult part of solving a problem. Nevertheless, there are some general steps that are often part of the modeling process and that you should consider following:

1. Identify the independent and dependent variables and assign letters to represent them. Most of the time the independent variable will be time. For example, in our flu model the number of susceptible, infected, and recovered individuals is changing as a function of time. In this case the number of susceptible, infected and recovered individuals are all dependent variables, since they depend on the value of time. Since you as the modeler control the time frame in which you wish to study the disease, time is an independent variable that does not depend upon any other factor.

2. Choose the units of measurement for each variable. In a sense, the choice of units is arbitrary, but

some choices may be much more convenient than others. For example, we choose to measure time in seconds when describing a fast process, such as a falling object. Yet one would use months when describing a slow process such as the growth of a human population, or days when modeling the flu infection across a population.

3. Articulate the basic principle or idea that underlies or governs the problem you are investigating.

This may be a widely recognized physical law, such as Newton’s law of motion, or it may be a more speculative assumption that may be based on your own experience or observations. In any case, this step is likely not to be a purely mathematical one, but will require you to be familiar with the field in which the problem originates. For our public health and disease spread applications, we might want to know details regarding the mode of transmission of a disease, the incubation time (if there is one) or even if there are pockets of a population that are immune to the disease at question.

4. Express the principle or law in step 3 in terms of the variables you chose in step 1 (Again, this is

normally time). This may be easier said than done as it may require the introduction of physical constants or parameters and the determination of appropriate values for them. Or it may involve the use of auxiliary or intermediate variables that must then be related to the primary variables.

5. Make sure that each term in your equation has the same physical units. This also includes all

your constants (i.e. infection rate and recovery rate). If this is not the case, then your equation is

Page 72: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 72 of 83

flawed and you should seek to repair it. If the units agree, then your equation at least is dimensionally consistent, although it may have other shortcomings that this test does not reveal. Again, you do not want to model the falling of an object in terms of days since you might miss the event completely or model the spread of a disease in terms of seconds since you will notice not much will happen within a short range of time.

The ultimate test of a mathematical model is whether its predictions agree with observations or experimental results. If the differences between actual observations and a mathematical model’s predictions are too great, then you need to consider refining the model, making more careful observations, or perhaps both. There is almost always a tradeoff between accuracy and simplicity. Both are desirable, but a gain in one usually involves a loss in the other. However, even if a mathematical model is incomplete or somewhat inaccurate, it may nevertheless be useful in explaining qualitative features of the problem under investigation. It may also give satisfactory results under some circumstances but not others. Thus you should always use good judgment and common sense in constructing mathematical models and in using their predictions.

Example: The Flu SIR Model In order to begin applying these general rules of mathematical modeling let’s recall our flu example and let’s build an SIR model based on this flu scenario. Again, let’s assume that we have a constant population, N, and that the population can be divided into three states; susceptible (S), infected (I), and immune (R). The first group, S, consists of individuals who are at risk of becoming infected with the flu. The second group, I, consists of individuals who are infected and can infect others. Sometimes these models include a class of exposed individuals, E, who are infected but cannot yet pass along the disease, for simplicity we leave out that scenario for now. Finally, group R represents those who have recovered from the disease and are immune to infection. A graphical representation or sketch of the basic relationship between our three groups and how they relate to one another is shown in the figure below. The arrows indicate the direction in which an individual can move from one group to another. The modeler should validate this representation before moving on. For example, notice how there is no arrow connecting the susceptible to the recovered group. This makes sense given an individual cannot go from the susceptible stage to the recovered stage without first having been part of the infected group. The infection and recovery rates are displayed above the arrows given they represent the rates at which the individuals move from one group to the other.

Page 73: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 73 of 83

Once the graphical representation of our scenario has been validated we can move on and begin constructing our system of differential equations. Using the diagram above, we can write a system of differential equations. The following set of equations represent the growth rates of each of the groups and is based on the movement of individuals from one group to the next as graphically represented in the figure above.

dSdt

= −i* S * I

dIdt

= i* S * I − r * I

dRdt

= r * I

(EQ 1.1)

We have established that an infection occurs as one infected individual comes in contact with a susceptible individual and that this infection rate is defined as “i,” whereas the recovery rate for an infected individual is represented by “r.” Therefore, we have that the susceptible population, initially consisting of the entire population minus those initially infected with the flu, loses members at a rate proportional to “i,” and the infected population loses members at a rate proportional to “r.” For example, group S loses members as each of its members comes into contact with a member in the infected group, and the interaction is represented mathematically by S*I. Such interaction will result in the infection of the individual in a manner proportional to the infection rate, “i”. Since this interaction results in a loss of individuals from group S, it is a negative interaction; therefore we conclude that S loses members at a rate mathematically represented by;

dSdt

= −i* S * I (EQ 1.2)

Similarly, the infected group decreases in size as the individuals in the group recover from the flu. Since the recovery is proportional to the number of people currently infected and the recovery rate, the mathematical term that represents this behavior is given by –r*I. Again these individuals are leaving this group; therefore the overall expression is negative. The infected group (I) is losing members as the

Page 74: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 74 of 83

individuals recover from the flu; on the other hand the infected group gains members as more individuals get infected. Since the individuals that leave the susceptible group are the same as those who are incorporated to the infected group the mathematical term that describes the phenomenon is given by

i* S * I . Note that this time the expression is positive since members are being added to the group. The net change in the group is therefore given by;

dIdt

= i* S * I − r * I. (EQ 1.3)

In a similar fashion the third equation is built based on the number of individuals who leave the infected group. Therefore, the equation that defines the change in the recovered group is given by;

dRdt

= r * I (EQ 1.4)

Note that this expression is the same as the one that describes the decrease in population in the infected group since those who leave the infected group are the same individuals that are incorporated into the recovered group. Once again this expression is positive since it represents an increase in population of the group. Incorporating a Computer into Mathematical Modeling A computer can be an extremely valuable tool in the study of differential equations. For many years computers have been used to execute numerical algorithms to construct numerical approximations to solutions of differential equations. A few lines of computer code, written in a high-level programming language and executed (often within a few seconds) on a relatively inexpensive computer, suffice to approximate to a high degree of accuracy the solutions of a wide range of differential equations. More sophisticated routines are also readily available. These routines combine the ability to handle very large and complicated systems with numerous diagnostic features that alert the user to possible problems as they are encountered. The usual output from a numerical algorithm is a table of numbers, listing selected values of the independent variable and the corresponding values of the dependent variable. With appropriate software it is easy to display the solution of a differential equation graphically, whether the solution has been obtained numerically or as the result of an analytical procedure of some kind. Such a graphical display is often much more illuminating and helpful in understanding and interpreting the solution of a differential equation than a table of numbers or a complicated analytical formula. What good is a computer model? The value of a model is that it allows a quantitative understanding of a phenomenon, permitting us to form hypotheses that we can then proceed to confirm or reject by applying the scientific method. Developing a math model of a disease outbreak, as we will do in this case, improves our understanding of the biology in action. Simulations allow performance of "what if" types of experiments. In business, "what if" capabilities are an important part of spreadsheet power, allowing business decisions to be made based on predicted consequences. What happens if I charge this much for my product? What if the cost of my raw materials increases by this much? What is the relationship between my profit margin and the number of product items I sell?

Page 75: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 75 of 83

Solving the SIR Differential Equation System Using Matlab Matlab is a numerical computing environment that allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces and interfacing with programs written in other languages, including C, C++, Java and Fortran. Matlab is also compatible with other more familiar programs such as Text and Excel. For our purposes, Matlab provides the framework necessary to solve our system of differential equations in a simple and effective manner. In order to solve our system of equations in Matlab, it is necessary to create two M-files. An M-file is a Matlab specific file in which the user may call a series of built-in Matlab functions, define systems of equations and define the corresponding parameters in a logical and well-organized manner. In our case the first M-file is used to define our system of equations, our constants such as the infection rate, “i”, and the recovery rate “r” and the name of our system of equations. The second M-file is used to define our initial and final time, and our initial conditions, such as the initial population in each of the three groups. The second M-file is also used to call the Matlab built-in ODE (Ordinary Differential Equation) solver to be used. In order to generate the two M-files needed to run our simulation we are to perform the following steps; Note: Each variable, code declaration, and Matlab command has to be inserted in a separate line. Do this by pressing the <Enter> key following the input of each of the desired commands.

1. First, in order to create a new Matlab M-file click on File -> New Script, this action will display a new empty M-file. Save the file by clicking File -> Save As and then inputing the desired name of the file and its location.

2. The first thing we will do with our new file is to declare it as a function. We do this by

writing the word function in the first line of the file, followed by the name of the file, filename, an equals sign, a space and then again filename followed by the variable used to define time (i.e. “t”) and the dependent variable to be modeled (i.e. “y”). The complete first line in our code should then look something like this; function filename = filename(t, y).

3. The next step is to list all the constants in the system of differential equations. Declare these

new constants on a new line by pressing <Enter>. We use different letters or names to define each of the constants such that no other constant or parameter has the same name. The execution of the code will result in an error. For the case of the flu model these constants include the infection rate (i) and the recovery rate (r). For simplicity, initially set these two values to a number between zero and one, for example i = 0.5 and r = 0.7.

4. The next step is the definition of the system of differential equations. We begin by defining

the first equation followed by a semicolon. Then we press <Enter> to input the next equation in a new line. We continue until all the equations have been defined. We make sure a semicolon follows each of the equations.

5. Once the system of equations has been defined, it is necessary to define the system of

equations as an array. This is done by placing the names of each of the equations inside brackets followed by an apostrophe ( ‘ ). This simplifies the execution of the code since all the equations are stored in a single array under the name filename. An example of the expression that accomplishes this task is given by, filename = [equation(1) equation(2) … equation(n)] ’;. See the Attachment ‘A’ below for an example of how steps 1-5 are incorporated into the M-file.

Page 76: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 76 of 83

6. The second M-file is used to define the initial conditions of the model as well as for calling

the ODE solver. Once again we start by opening a new M-file. To create a new Matlab M-file click on File -> New Script, this action will display a new empty M-file. We save the file by clicking File -> Save As and then input the desired name of the file and its location.

7. Once the file has been saved, begin creating the code by defining the initial time (normally

zero or one) and the final time for your simulation. Note that both the initial and final time must be defined independently using a valid name for each of them. For example use, t_0 = 1, to declare the initial time and t_f = 100, to declare the final time. After each of the declarations remember to press <enter>.

8. The next step is the declaration of the initial conditions of each of our populations. For

example we have to define the number of members in each of the susceptible, infected and recovered groups. The task is completed by using a single variable in an array form, where each member of the array represents the corresponding population in each of the equations in the system. Normally in the case of the flu simulation, where your population is for example 100, you would have 99 people susceptible, one person infected and zero people recovered. This condition can then be entered using P_init = [99 1 0].

9. Next we need to call our ODE solver. There are multiple solvers available in Matlab and

each of them offers characteristics that might be useful for solving systems of equations under various conditions. For our purpose the ODE45 solver is perfect. We call the solver by inputting the initial and final time as well as the array that contains the initial conditions. The output will contain a matrix “y” with the populations of the various groups as well as the corresponding time. The input is in the form [t, y] = ode45( ‘filename’, [initial_time, final_time], initial_conditions). The expression [t, y], refers to the output that will be received and printed later, whereas the ‘filename’ refers to the previously created M-file where the system of equations was defined.

10. The last step is the plotting of the data to verify that our model correctly describes the

behavior we wish to model. Do this by calling the plot function by using plot( ). Remember that the output data is in the form of a matrix and that each of the rows of the matrix contains the data for each of the populations. If you call, plot(t, y(:,1)), Matlab will plot all the numbers in the first column of the matrix. The colon sign is used to define “all members.” For example, the command plot((t, y(:,2)) would be used to plot all the data points in the second column of matrix “y.” See Attachment ‘B’ for an example of how steps 6-10 are incorporated into the M-file.

Following these steps and using the system of equations for the SIR model you should be able to generate a graph that looks similar to the one displayed below (depending upon the values of your parameters). We can see how initially towards the left of the graph (initial time), all the members of the population, except for 1, belong to the susceptible group, whereas 1 member of the total population belongs to the infected group. As time goes on, the susceptible group loses members as more and more people become infected. Once infected, these individuals recover to join the recovered group. Towards the right of the graph (final time), we see that the majority of the population belongs to the recovered group. The behavior of the three graphs can vary dramatically depending upon the values of the infection and recovery rates.

Page 77: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 77 of 83

More characteristics can be added to the basic model presented in this brief introduction. These characteristics can increase the complexity of the model but can also offer a deeper insight into the understanding of epidemics in a population. What changes do you think you would incorporate and how would you achieve those changes? What other information could you collect and how would your model and understanding of an epidemic benefit from the collection of this additional information? Expanding the SIR Matlab Project The model that we have just created is an over-simplified model for the modeling of a disease outbreak in a population. We have failed to incorporate death, birth rate, and incubation period just to name a few factors. We do not need to incorporate all those factors into our model at once as that would complicate things, but we can slowly add complexity to our model verifying that our final outcome reflects what one would expect as a certain factor is added to our system of equations. There are other factors, which are important in other diseases that are not necessarily a factor in diseases that behave according to the SIR model. For example, there are diseases that will affect men more than women or vice versa. There are also diseases that will affect children more than adults. Most importantly, there are factors such as temperature, water quality, air quality, rainfall, humidity and other environmental factors that can greatly affect the rates at which a disease spreads through a population. These are all important considerations to take when you are brainstorming about the factors, which will be included in your model. Again, let’s remind ourselves that mathematical modeling is as much an art as a science and that like anything, it takes time to gain expertise and be proficient in it, so be patient, and as any other artistic and scientific activity, mathematical modeling can get to be an exciting and rewarding experience.

Page 78: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 78 of 83

Take Home Questions for Your Matlab SIR Model

How would you incorporate death into the model you have just created? Suppose that after a person is infected with the disease, the person can either recover or die. How would this option be incorporated into the system of equations? How would you incorporate an incubation period or delay into the model. In our current version of the SIR model we assume that the person who has been infected can immediately infect others. Let’s assume this is not the case, and that the person who becomes infected cannot infect others until after a given period of time. How would this feature be incorporated into our system of equations? Assume that men are affected more than women by a certain disease that behaves according to the SIR model. How can we add this feature into our model? Would you separate men and women into different groups (described by different differential equations)? Would you keep them in the same group? What other method(s) can you device to incorporate this feature into your model?

What additional questions would you ask?

Page 79: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 79 of 83

8. - Case Study #6 – BUILDING AN SIR SYSTEM USING CELLULAR AUTOMATA

Goals of the Project:

1. Layout the strategy to be used for the project (Neighborhood Scheme, Different Disease States, Boundary Conditions, etc). Explain why you have chosen to implement that neighborhood scheme.

2. Create SIR Model Using Cellular Automata Using Matlab

a. Establish basic model b. Set parameters, variables, etc c. Set neighborhood conditions, random number generator, and necessary for- or while-

loops. d. Create basic visualization strategy e. Run basic model and adjust to meet expected behavior

3. Incorporate a coloring scheme of disease states. Each disease state should have a different color.

4. Perform comparisons of the results obtained using different values for specific parameters in the

model and make evaluations and suggestions for improving the model.

5. Perform at least one improvement you think will enhance the model and explain how that improvement affects the accuracy, precision, efficiency or understanding of the model.

6. Pretend for a minute that you are a public health official. Based on your simulations, is there a

strategy you would implement to minimize the impact of the disease on the population under your care? For example, would you propose providing vaccines or minimizing the contact with the neighbors? Any other strategies you can think of?

7. What are the advantages and disadvantages of using cellular automata to model the spread of

diseases? What factors are not included in the model you have created?

8. Simulate a diversified geographical area through which the disease is spreading (i.e. Higher or lower susceptibility in certain areas, different temperatures, etc.).

What to Submit: Submit a report on the work completed along with your commented code, any simulations and resulting figures you might have produced, along with any conclusions you were able to draw from those simulations. Comment on the accuracy of the model and any ideas you might have for improving the modeling process of infectious diseases or any other physical, biological or chemical event using cellular automata. Remember to be explicit with your explanations. Provide full sentences and organize your thoughts into paragraphs that explain why things were done in a certain way. Incorporate the logic behind each of the actions that were made. Make sure you include any necessary equations and figure. Number them and provide captions where necessary.

Page 80: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 80 of 83

9. - CLOSING REMARKS AND REFERENCES It is our hope that by reading this guide you formed a general idea of the capabilities of MATLAB, while obtaining a working knowledge of the program while utilizing mathematical modeling methods. Certain advantages but also limitations of MATLAB could also be seen through this tutorial, and it is left to the reader to decide when and if to use this program. A good source of information related to MATLAB can be found at www.mathworks.com. It is strongly recommended that you visit this web page to see what other publications (if any) exist that will allow you to enhance your knowledge of MATLAB. Some are more advanced than others so do not hesitate to talk to your professor for guidance through the (rather) long list. http://www.mathworks.com/support/ The above web page includes a link to MATLAB based books. See also http://www.mathworks.com/support/books/index.jsp

Page 81: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 81 of 83

10. - ATTACHMENTS

Attachment ‘A’ - MATLAB File #1

% This Matlab code is one of two necessary files to run the SIR model.% This file declares the initial and final time to be included in the model% and the initial conditions of the population. The code them makes a call% to Matlab file 'ypsir' to solve the model given the initial conditions% stated. Once the code receives the output from 'ypsir' the code% generates a figure with the generated results.clear all;

% Declares time zero and final time of the model.to = 0;tf =50;

% Declares the number of individuals in each of the groups in the model at% time zero. This is known as the initial conditions of the population.yo = [99 1 0];

% Makes a call to 'ypsir' to solve the system of equations given the% initial conditions.[t y] = ode45('ypsir',[to tf],yo);

% Creates figure to display the results obtained from 'ypsir' in the form% of t (time) and y (matrix containing the results from the three groups in% the model).figure1 = figure('XVisual','');% Create axesaxes1 = axes('Parent',figure1,'YGrid','on','XGrid','on','FontSize',14,...

'FontName','Arial');box(axes1,'on');hold(axes1,'all');% Plot Dataplot1 = plot(t,y(:,1),'b', t,y(:,2),'r',t,y(:,3),'g');set(plot1(1),'Color',[0 0 1],'DisplayName','Susceptible');set(plot1(2),'Color',[1 0 0],'DisplayName','Infected');set(plot1(3),'Color',[0 1 0],'DisplayName','Recovered');% Create titletitle('Simple SIR Model','FontSize',16,'FontName','Arial');% Create xlabelxlabel('time','FontSize',16,'FontName','Arial');% Create ylabelylabel('Susceptible, Infected, Recovered','FontSize',16,'FontName','Arial');% Create legendlegend1 = legend(axes1,'show');set(legend1,...

'Position',[0.739651268115942 0.513826504784941 0.0989583333333333 ...0.101228978007762]);

1

Page 82: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 82 of 83

Attachment ‘B’ – MATLAB File #2

% This Matlab code is one of two necessary files to run the SIR model.% This file declares the necessary parameters and the system of% differential equations of the model. The last line of the code arranges% the system of equations into an matrix(array).function ypsir =ypsir(t,y)

% Declaration of parameters used by the system of equations.i = 0.01;r = 0.1;

% Simple SIR Model Declaration of Differential Equationsypsir(1) =-i*y(1)*y(2);ypsir(2) = i*y(1)*y(2)-r*y(2);ypsir(3) = r*y(2);

% Arrangement of the system of equations into a matrix(array)ypsir = [ypsir(1) ypsir(2) ypsir(3)]';

Input argument "y" is undefined.

Error in ==> ypsir at 12ypsir(1) =-i*y(1)*y(2);

Published with MATLAB® 7.11

1

Page 83: MATHEMATICALLY MODELED AREA · 2013-11-07 · freshman-sophomore college level, and has a steeper learning curve. The further use of this software will be left as optional for those

Page 83 of 83

11. - REFERENCES Bender, Edward A. (1978). An Introduction to Mathematical Modeling. Mineola, New York, USA: Wiley. Boyce, William E. & DiPrima, Richard, C. (2005). Elementary Differential Equations and Boundary Value Problems. Eight Edition. New York, USA: Wiley. Jones, D. S. and Sleeman. (2003). Differential Equations and Mathematical Biology. Boca Raton, Florida, USA: Chapman & Hall / CRC. Shiflet, Angela B. and Shiftlet, George W. (2006). Introduction to Computational Science. New Jersey, USA: Princeton University Press. Xenophontos, Christos. A Beginner’s Guide to MATLAB. Department of Mathematical Seiences, Loyola University, USA.