matlab manual kerickson
TRANSCRIPT
-
8/4/2019 MATLAB Manual KErickson
1/22
MATLAB
User Guide for Chemical and BiologicalEngineering MajorsVersion 1.0
By Kristin Erickson
Engineering Dept. at Colorado State University
1113 Hillcrest Dr.
Fort Collins, CO 80521
mailto:[email protected]:[email protected]:[email protected] -
8/4/2019 MATLAB Manual KErickson
2/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 1 -
Table of Contents
Page
Preliminary pages1-2
Chapter 1About this Manual..3
1.1 Introduction ...31.2 Scope and Purpose.31.3 Targeted Audience.31.4 Manual Organization....3-4
Chapter 2Introduction5
Chapter 3Getting Started...6
3.1 Program Window.6-7
3.2 Assigning Variables to Numbers and Matrices.8
3.3 Matrices9-10
3.4 Arrays and Vectors10
3.5 Creating an m-file..11
Chapter 4Plotting in Two Dimensions.12-14
Chapter 5Common Commands15
5.1 Reserved Words or Symbols15
5.2 Importing Data From Excel..16-17
Chapter 6 - Debugging.18-19
References20
-
8/4/2019 MATLAB Manual KErickson
3/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 2 -
List of Illustrations
Figure Page
Figure 1 : Initial MATLAB Screen .6
Figure 2 : Workspace Window7
Figure 3 : Example 2D Graph....12
Figure 4 : Example Graph-Two Data Sets.14
Table 1 : Matrix Operations ...10
Table 2 : Common Reserved Words or symbols15
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.
-
8/4/2019 MATLAB Manual KErickson
4/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 3 -
Chapter 1About this Manual
1.1 IntroductionThis manual offers a basic overview and instruction on the Mathworks computer software
program, MATLAB, which is a contraction of Matrix Laboratory.
1.2 Scope and PurposeThis manual provides the following:
An overview of the MATLAB software program and its application Explanations of computing concepts and their implementations General debugging instructions
1.3 Targeted AudienceThe 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 OrganizationThe manual is divided into the following chapters:
Chapter 1About this Manual discusses the manuals scope and purpose, targeted
audience and the organization.
Chapter 2Introduction and Application gives an overview of the capabilities of
MATLAB and how the program can be used in the future.
Chapter 3Getting Starteddiscusses some basic concepts of computing and introduces
the operation of the MATLAB user interface.
Chapter 4Plotting introduces the two dimensional graph and associated commands.
-
8/4/2019 MATLAB Manual KErickson
5/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 4 -
Chapter 5Common Commands takes the reader through common techniques used to
execute a series of operations.
Chapter 6Debugging discusses the most frequent error messages that appear in the
program.
Throughout this manual, courierfont will be used to denote words, symbols or
numbers typed into MATLAB.
-
8/4/2019 MATLAB Manual KErickson
6/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 5 -
Chapter 2Introduction and Application
The MATLAB software is one of the most efficient mathematical computer programs available
and specializes in matrices. As a Chemical and Biological Engineer, MATLAB will become a
common workmate by graduation day. The program is highly favored and respected by multiple
professors at Colorado State University in the Chemical and Biological Engineering (CBE)
Department. Those who are diligent to learn the basics in the first year will automatically be far
ahead of the rest. This manual provides the reader with knowledge covered in the first year of
CBE.
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.
-
8/4/2019 MATLAB Manual KErickson
7/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 6 -
Chapter 3Getting Started
3.1 Program Window
To open MATLAB, click on the MATLAB R2010a button in the start menu. The
program should appear similar Figure 1 without the highlighted colors.
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
-
8/4/2019 MATLAB Manual KErickson
8/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 7 -
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, if5+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.
-
8/4/2019 MATLAB Manual KErickson
9/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 8 -
3.2 Assigning Variables to Numbers and Matrices
MATLAB can store any number or matrix as a specific variable name. Ifx=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/4/2019 MATLAB Manual KErickson
10/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 9 -
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 mustbe of equal size. Review the example below.
>>A=[2 3;4 5]
>>B=[6 7; 8 9]
This simply means that the matrix [ ] is assigned to the variable A and [ ] is
assigned to the variable B.
>>C=A*B
C =
36 41
64 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
-
8/4/2019 MATLAB Manual KErickson
11/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 10 -
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-by-
element multiplication was desired. For element-by-element division and power raising,
the period symbol needs to be placed in front ofdivision 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.
Table 1. Matrix Operations>>A This transposes the matrix A>>eye(3) Creates a 3x3 matrix with ones along the diagonal
>>inv(B) Computes the inverse of B
>>A\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
-
8/4/2019 MATLAB Manual KErickson
12/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 11 -
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 m-
file, press the button.
-
8/4/2019 MATLAB Manual KErickson
13/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 12 -
Chapter 4Plotting in Two Dimensions
For a CBE major, two dimensional plots will be made on a regular basis. There are many
formatting commands associated with these plots, so it is important to learn these as quick as
possible. It is always best to design plots in an m-file. Figure 3 shows the output from the
following commands below.
x=1:10
y=2:2:20
plot(x,y,'bo')
title('Plant Growth')
xlabel('Time [days]')
ylabel('Height [inches]')
-
8/4/2019 MATLAB Manual KErickson
14/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 13 -
Figure 3. Example 2D Graph
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 plotinto 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 helplegend in the command
window.
-
8/4/2019 MATLAB Manual KErickson
15/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 14 -
Figure 4. Example Graph-Two Data Sets
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 -
-
8/4/2019 MATLAB Manual KErickson
16/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 15 -
Chapter 5Common Commands
5.1 Reserved Words or Symbols
Because there is no key on a standard computer for a square root sign, MATLAB has
programmed in reserved words for specific functions. To take the square root of 64, the
user would type sqrt(64) and MATLAB would return the number 8. Table 2 shows a
list of common commands that are programmed into MATLAB, where n denotes any
number.
Table 2. Common Reserved Words or Symbols
sqrt(n) Takes the square root of n
sin(n) Takes the sine of ncos(n) Takes the cosine of n
tan(n) Takes the tangent of n% Allows the user to comment any line in an
m-file. Any typing after the % will not be
executed as a command.; Suppresses the output in the command
window if added after a line of code
abs(n) Takes the absolute value of nfloor(n) Rounds any decimal down
ceil(n)Rounds any decimal upround(n) Rounds by standard rounding rules
log(n) Takes the natural log of a numberlog10(n) Takes the log base 10 of a numbermin(n) Outputs the minimum of each column in a
vector or matrixmax(n) Outputs the maximum of each column in a
vector or matrixmean(n) Outputs the mean of each column in a
vector or matrixsum(n) Outputs the sum of each column in a vector
or matrixlength(n) Outputs the length of vector n
pi
-
8/4/2019 MATLAB Manual KErickson
17/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 16 -
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 =
oven1: [42x15 double]
oven2: [41x15 double]
-
8/4/2019 MATLAB Manual KErickson
18/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 17 -
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.
-
8/4/2019 MATLAB Manual KErickson
19/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 18 -
Chapter 6Debugging
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.
3.
Error: Expression or statement is incorrect--possibly
unbalanced (, {, or [.
-
8/4/2019 MATLAB Manual KErickson
20/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 19 -
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.
-
8/4/2019 MATLAB Manual KErickson
21/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 20 -
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.
.
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.
-
8/4/2019 MATLAB Manual KErickson
22/22
Erickson MATLAB for Chemical and Biological Engineering Majors
- 21 -
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