Professional Documents
Culture Documents
MATLAB Manual KErickson
MATLAB Manual KErickson
By Kristin Erickson Engineering Dept. at Colorado State University kristin.erickson@rams.colostate.edu 1113 Hillcrest Dr. Fort Collins, CO 80521
Erickson
Table of Contents Page Preliminary pages1-2 Chapter 1 About this Manual..3 1.1 1.2 1.3 1.4 Introduction...3 Scope and Purpose.3 Targeted Audience.3 Manual Organization....3-4
Chapter 2 Introduction5 Chapter 3 Getting Started...6 3.1 3.2 3.3 3.4 3.5 Program Window.6-7 Assigning Variables to Numbers and Matrices.8 Matrices9-10 Arrays and Vectors10 Creating an m-file..11
Chapter 4 Plotting in Two Dimensions.12-14 Chapter 5 Common Commands15 5.1 5.2 Reserved Words or Symbols15 Importing Data From Excel..16-17
-1-
Erickson
Figure 1 : Initial MATLAB Screen .6 Figure 2 : Workspace Window7 Figure 3 : Example 2D Graph....12 Figure 4 : Example Graph-Two Data Sets.14
Notification: This manual does not cover all necessary components for excelling in the lower level CBE classes. It merely introduces the student to the program and provides extended knowledge and examples on confusing subjects related to MATLAB.
-2-
Erickson
Targeted Audience The intended audience for this manual is first and second year Chemical and Biological Engineering students at Colorado State University. It is assumed that the students all have pre-Calculus math knowledge. This information is not secluded to other universities, but may not provide all the pertinent material to be used elsewhere.
1.4
Manual Organization The manual is divided into the following chapters: Chapter 1 About this Manual discusses the manuals scope and purpose, targeted audience and the organization. Chapter 2 Introduction and Application gives an overview of the capabilities of MATLAB and how the program can be used in the future. Chapter 3 Getting Started discusses some basic concepts of computing and introduces the operation of the MATLAB user interface. Chapter 4 Plotting introduces the two dimensional graph and associated commands.
-3-
Erickson
Chapter 5 Common Commands takes the reader through common techniques used to execute a series of operations. Chapter 6 Debugging discusses the most frequent error messages that appear in the program. Throughout this manual, courier font will be used to denote words, symbols or numbers typed into MATLAB.
-4-
Erickson
The reader will learn that MATLAB possesses more capabilities than that of a TI-89 calculator. MATLAB is used frequently in the CBE 201 course and is used heavily in CBE 330, 332, 333 and 433. Profound knowledge of the program is highly beneficial for the latter two courses listed as these are lab sequences and both require 200+ hours of data analyzing. Additionally, numerous homework problems may ask for repetitive calculations and can easily be completed with MATLAB.
-5-
Erickson
Figure 1. Initial MATLAB screen The red highlighted portion is the current directory that MATLAB is working from. As Figure 1 shows, it currently in the folder, MATLAB. This always needs to be changed as soon as MATLAB is opened. Click on the << and choose the U: drive. This assures that all information will be saved to the personal U: drive that Colorado State University provides the engineering students. Next, create a folder by right clicking in the red area so all files created in MATLAB will be organized. As a suggestion, title the new folder as the class code. Open the new created folder to continue on.
-6-
Erickson
The blue highlighted area is the command window where commands can be typed into. It is important to wait until the double arrows >> appear in the command window before any typing occurs. As an exercise, type in math calculations you might type into a calculator to experience how the command window works. Note: The * symbol signifies multiplication, the / symbol signifies division and the enter key tells MATLAB to execute the typed in command. Be sure to use parenthesis appropriately, just as they would be used on an advanced calculator.
Once any commands are typed into the command window, they will appear in the highlighted green box. This is the command history window. By double clicking on any command in the history window, MATLAB will execute the command once again.
The orange box is the workspace. This lists all the values that MATLAB has stored as a variable. For example, if 5+3 is typed into the command window and enter is pressed, the workspace will appear as shown in Figure 2.
Figure 2. Workspace Window This figure tells the user that variable named ans has a value of 8.
-7-
Erickson
3.2
Assigning Variables to Numbers and Matrices MATLAB can store any number or matrix as a specific variable name. If x=6 is typed into the command window, MATLAB will assign the variable x to be the number 6. If x+6 is then typed into the command window, MATLAB will output a value of 12. A variable can be any name the user chooses. For example, if the mass and volume of a substance is known and density is to be calculated, the user might type in the following commands: >>mass=100 >>volume=103 >>density=mass/volume This now has assigned the variable mass to be 100, volume to be 103 and density to be 0.9709. It is pertinent to keep in mind that if the user is assigning a numerical value to a variable, the variable name must be typed first, followed by an equals sign.
To enter a matrix into MATLAB, the bracket symbols are used as shown below. >>[1 2 3 4] This configuration of typing will create a 2x2 matrix with numbers 1 and 2 in the top row and numbers 3 and 4 in the bottom row. Another way to type this same matrix into MATLAB is: >>[1 2;3 4] The semi-colon denotes the start of a new row. The entries in a matrix must be separated by a space to denote a single number. Keep in mind that matrices must be square or
-8-
Erickson
rectangular and any standard operation must follow matrix rules. Just as shown above with assigning a variable to a number, the same exact step goes for a matrix. 3.3 Matrices The majority of the work a CBE major experiences deals with element-by-element manipulation of a matrix. This means that when multiplication or division operations are performed with two matrices, the normal matrix rules so not apply. Instead, the corresponding elements from the same row and same column undergo the desired operation. In this instance, the matrices must be of equal size. Review the example below. >>A=[2 3;4 5] >>B=[6 7; 8 9] This simply means that the matrix [ assigned to the variable B. >>C=A*B C = ] is assigned to the variable A and [ ] is
36 64
41 73
This is the standard matrix multiplication and MATLAB has now assigned the variable C to the matrix answer of A times B, [ >> C=A.*B C = ].
12
21
-9-
Erickson
32
45
This second example is the element by element multiplication of matrices A and B (2 x 6=12, 3 x 7=21, etc.) Notice the period symbol was added to indicate that element-byelement multiplication was desired. For element-by-element division and power raising, the period symbol needs to be placed in front of division and carrots signs as well. The period symbol is not needed for matrix addition and subtraction because those operations already indicate element-by-element manipulation. Table 1 below shows other matrix manipulation tools assuming A and B are as given in the above example. >>A >>eye(3) >>inv(B) >>A\B Table 1. Matrix Operations This transposes the matrix A Creates a 3x3 matrix with ones along the diagonal Computes the inverse of B Computes the inverse of A times B
3.4
Arrays and Vectors An array is essentially a 1xn matrix in MATLAB, where n denotes any integer greater than 1. A vector is an nx1 matrix. If a 1x100 sequential array structure is desired for computation, the user does not have to type out the numbers one through 100 in a matrix. Instead, there are two ways in which this array can be created. >> 1:1:100 >> linspace(1,100,100) Both of these entries create a 1x100 array from one to one hundred in sequential order. In the first entry, the first slot denotes the start number, the second slot represents the step size and the last slot is the end number. If a 2 were placed in the middle slot, the matrix would start at 1 and then list all the odd numbers up to 99. If the middle entry is left out, a step size of one is assumed. In the second entry, the first slot denotes the start number, the
- 10 -
Erickson
second slot represents the end number and the last slot generates that number of points between the start and stop numbers. If the last slot is left out, it is assumed that the user wants 100 points between the start and stop numbers. Both commands may seem similar, but are used in different cases depending on what the user is attempting to do. 3.5 Creating an m-file An m-file in MATLAB is a way to store a list of commands and then be able to run them all at the same time. An m-file is created by clicking the icon in the top left corner. A
blank script file called Editor will appear. It is always a good idea to immediately type the following two lines in an m-file so the command window is cleared and all the variables are cleared each time the m-file is run. clc clear An m-file is exactly like the command window except when enter is pressed, the cursor goes to the next line and is ready for the user to type another line of code. To run an mfile, press the button.
- 11 -
Erickson
- 12 -
Erickson
In line 1 from the commands above, a 1x10 array from 1 to 10 was made. In line 2, the array [2 4 6 8 10 12 14 16 18 20] was made. Line 3 told MATLAB to plot these two arrays and make blue circles for each point. The b was for blue and the o was for circle points. By typing help plot into the command window, a list of colors and marker shapes can be seen. If no color or marker shape is commanded, an automatic blue line connecting the points is created. The fourth line titled the graph, Plant Growth, while the fifth and sixth lines titled the x and y axis accordingly. This exact format of lines 3-6 needs to be typed into MATLAB to form a properly labeled graph.
If two sets of data wish to be plotted on the same graph, the following commands should be used. plot(x,y,'bo',y,x,'gx') title('Plant Growth') xlabel('Time [days]') ylabel('Height [inches]') legend('Dandelion','Hibiscus','Location','SouthEast') In line 1, this tells MATLAB to also plot x versus y and make those points green xs. The last line directs MATLAB to put a legend in the southeast corner of the graph and to name the blue circles, Dandelion, and the green xs, Hibiscus. The output from this plot is shown below as Figure 4. Other positions of the legend can be found by typing help legend in the command window.
- 13 -
Erickson
When an m-file is being used to run a program, it is helpful to add close all so that MATLAB closes all the figures before the program is run again in case changes were made. Additionally, if multiple graphs are being made in an m-file, the command figure(n) must be placed in the line before plot so as to assign the graph to a figure numbered n, where n is an integer. It is highly suggested to visit mathworks.com as an endless amount of graphing features can be learned about plotting.- 14 -P a g e | - 14 -
- 14 -
Erickson
- 15 -
Erickson
5.2
Importing Data into Excel To import excel data into MATLAB, both the data and the m-file in which the data is being imported into must be saved in the same folder and must be saved with a .xls extension. To import the data from an excel spreadsheet titled, MassOfBody.xls, the following command must be used: X=importdata('MassOfBody.xls') This assigns the data being imported to the variable X. Many times MATLAB reads the data as a structure. To open a structure, periods are added to the extension. For example, the output from the command above might be: X =
data: [1x1 struct] textdata: [1x1 struct] colheaders: [1x1 struct] This means that within X, there are a 1x1 structures that MATLAB named data, textdata and colheaders. Since the goal is often to manipulate and analyze data, all the user is concerned with are the numbers that MATLAB imported. These are always going to be listed under data. To open this structure and name it as a new variable, type Y=X.data. If there are multiple pages of spreadsheets in excel then the output from MATLAB might now look like: Y =
Erickson
oven3: [39x15 double] oven4: [38x15 double] This means there were four spreadsheets titled oven1, oven2, oven3 and oven4 and they each contain n x n amount of data. Once again, to open one of these structures the user would type Y=X.data.oven1. The numbers have now been imported and are ready to be manipulated.
- 17 -
Erickson
Chapter 6 Debugging
Because software programs follow exact orders, they will not run completely if there is even a single error in what the user has typed in. Although it may be obvious, they will not fix the users problem on their own. Instead, MATLAB responds to errors with pre-programmed messages that are often unclear to first time users. The following list below shows common ambiguous error messages and their meanings in more understandable terms.
1. ??? Error using ==> vertcat CAT arguments dimensions are not consistent. The dimensions of a matrix typed in somewhere are not square or rectangular. This could also be a response to invalid matrix addition, subtraction, division or inversion.
2. ??? Undefined function or variable 'b'. The variable b is not assigned a number.
- 18 -
Erickson
There are too many or too little (, {, or [. Check to make sure they are all balanced.
4. ??? Error using ==> importdata at 136 Unable to open file. MATLAB does not have the excel file open in the current directory.
5. >> ??? ` | Error: The input character is not valid in MATLAB statements or expressions. MATLAB does not recognize the symbol typed in.
For additional help with MATLAB, the Mathworks website is able to answer almost any posed question. Also, the command lookfor can be followed by a space and then the subject in question for a display of commands having to do with the particular topic.
- 19 -
Erickson
References
1. Dr. Bradley Reisfeld, Colorado State University, Associate Professor for the Department of Chemical and Biological Engineering, Ph: (970) 491-1019 2. MathWorks - MATLAB and Simulink for Technical Computing. Web. 07 June 2011. <http://www.mathworks.com>. 3. Smith, David M. Engineering Computation with MATLAB. Boston: Pearson/Addison Wesley, 2008. 4. Hanselman, D. Littlefield, B. Mastering Matlab. Usa: Prentice Hall Internation, 1996.
- 20 -
Erickson
Glossary
array: an ordered set of numbers in a horizontal 1xn matrix command window: the area in which commands are executed in MATLAB and outputs appear directory: the area in which folders are open and MATLAB will run from m-file: a script written in MATLAB containing a function or sequence of commands matrix: a square or rectangular array of numbers in rows and columns that can be manipulated according to matrix rules vector: an ordered set of numbers in a vertical nx1 matrix
- 21 -