Matlab Mod
Matlab Mod
Introduction to MATLAB
The purpose of this module1 is to review MATLAB for those that have used it before, and to provide a brief introduction to MATLAB for those that have not used it before. This is a "handson" tutorial introduction. After using this tutorial, you should be able to: 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10 1.11 1.12 1.13 1.14 1.15 enter matrices make plots write simple m-files Background Using this tutorial Entering matrices The MATLAB workspace Complex variables Matrix multiplication Plotting More matrix stuff FOR loops and IF-THEN statements m-files Diary Toolboxes Limitations to Student MATLAB Contacting MATHWORKS Summary of Commands perform matrix operations use MATLAB functions
1 A good reference is Introduction to MATLAB For Engineers and Scientists by D.M. Etter (Prentice Hall, 1996).
Module 1. MATLAB
1.1
Background
MATLAB is an interactive program for numerical computation and data visualization. It was originally developed in FORTRAN as a MATrix LABoratory for solving numerical linear algebra problems. The original application may seem boring (except to linear algebra enthusiasts), but MATLAB has advanced to solve nonlinear problems and provide detailed graphics. It is easy to use, yet very powerful. A few short commands can accomplish the same results that required a major programming effort only a few years ago.
1.2
This tutorial provides a brief overview of essential MATLAB commands. You will learn this material more quickly if you use MATLAB interactively as you are reviewing this tutorial. The MATLAB commands will be shown in the following font style:
Monaco font
the prompt for a user input is shown by the double arrow
sometimes you do not know the exact command to perform a particular operation. In this case, one can simply type
help
and MATLAB will provide a list of commands (and m-files, to be discussed later) that are available. If you do not know the exact command for the function that you are after, another useful command is lookfor. This command works somewhat like an index. If you did not know the command for the exponential function was exp, you could type
Matrix exponential via Pade' approximation. Matrix exponential via Taylor series approximation. Matrix exponential via eigenvalues and eigenvectors. Used by LINSIM to calculate matrix exponentials.
Entering Matrices
The basic entity in MATLAB is a rectangular matrix; the entries can be real or complex. Commas or spaces are used to delineate the separate values in a matrix. Consider the following vector, x (recall that a vector is simply a matrix with only one row or column)
x = [1,3,5,7,9,11] x= 1 3 5 7 9 11
Notice that a row vector is the default. We could have used spaces as the delimiter between columns
x = [1 3 5 7 9 11] x= 1 3 5 7 9 11
There is a faster way to enter matrices or vectors that have a linear pattern. For example, the following command creates the previous vector
x = 1:2:11 x= 1 3 5 7 9 11
transposing a row vector yields a column vector ( ' is the transpose command in MATLAB)
y = x' y= 1 3 5 7 9 11
If we want to make x a column-vector we use a semicolon as the delimeter between rows
Module 1. MATLAB
x = [1;3;5;7;9;11] x= 1 3 5 7 9 11
To make x a row vector gain, we use the transpose
x = x'
Say that we want to create a vector z, which has elements from 5 to 30, by 5's
z = 5:5:30 z= 5 10 15 20 25 30
If we wish to suppress printing, we can add a semicolon (;) after any MATLAB command
z = 5:5:30;
the z vector is generated, but not printed in the command window. We can find the value of the third element in the z vector, z(3), by typing
z(3) ans = 15
Notice that a new variable, ans, was defined automatically.
ans
Grand total is (19 * 8) = 152 bytes, leaving 622256 bytes of memory free.
We can also find the size of a matrix or vector by typing
[m,n]=size(x) m= 1 n= 6
where m represents the number of rows and n represents the number of columns. If we do not put place arguments for the rows and columns, we find
size(x) ans = 1 6
length(x) ans = 6
Module 1. MATLAB
It should be noted that MATLAB is case sensitive with respect to variable names. An X matrix can coexist with an x matrix. MATLAB is not case sensitive with respect to "built-in" MATLAB functions. For example, the length command can be upper or lower case
LENGTH(x) ans = 6
Notice that we have not named an upper case X variable. See what happens when we try to find the length of X
clear
more frequently you may wish to clear a particular variable, such as x
clear x
this is particularly true if you are performing a new calculation of x and the new vector is shorter than the old vector. If the new vector has length n, then all of the elements of the new x greater than x(n) will contain values of the previous x vector. You may wish to quit MATLAB but save your variables so you don't have to retype or recalculate them during your next MATLAB session. To save all of your variables, use
save file_name
(saving your variables does not remove them from your workspace; only clear can do that) You can also save just a few of your variables
save file_name x y z
To load a set of previously saved variables
load file_name
1.5
Complex variables
1.5 Complex Variables Both i and j represent the imaginary number, -1, by default
b = [1 2 3;4 5 6] b= 1 4
using the
2 5
3 6
c = a*b c=
Module 1. MATLAB
d = c.*b d= 1.0e+02 * 0.0600 0.1800 0.3600 -0.8000 + 0.0800i -1.2500 + 0.2000i -1.8000 + 0.3600i
(notice the scaling that is performed when the numbers are displayed) Similarly, element by element division,b(i,j)/c(i,j), can be performed using ./
e = b./c e= 0.1667 0.2222 0.2500 -0.1980 - 0.0198i -0.1950 - 0.0312i -0.1923 - 0.0385i
Other matrix operations include: (i) taking matrix to a power, and (ii) the matrix exponential. These are operations on a square matrix
f = a^2 f= 4.0000 + 2.0000i -3.0000 0 - 6.0000i 25.0000 + 2.0000i g = expm(a) g= 7.2232 + 1.8019i 1.0380 + 0.2151i -0.4302 + 2.0760i -0.0429 + 0.2962i
1.7 Plotting
plot(x,z)
1.7 Plotting
xlabel('x') ylabel('z')
For more plotting options, type
help plot PLOT Plot vectors or matrices. PLOT(X,Y) plots vector X versus vector Y. If X or Y is a matrix, then the vector is plotted versus the rows or columns of the matrix, whichever lines up. PLOT(X1,Y1,X2,Y2) is another way of producing multiple lines on the plot. PLOT(X1,Y1,':',X2,Y2,'+') uses a dotted line for the first curve and the point symbol + for the second curve. Other line and point types are: solid dashed dotted dashdot -: -. point plus star circle x-mark . + * o x red green blue white invisible arbitrary r g b w i c1, c15, etc.
PLOT(Y) plots the columns of Y versus their index. PLOT(Y) is equivalent to PLOT(real(Y),imag(Y)) if Y is complex. In all other uses of PLOT, the imaginary part is ignored. See SEMI, LOGLOG, POLAR, GRID, SHG, CLC, CLG, TITLE, XLABEL YLABEL, AXIS, HOLD, MESH, CONTOUR, SUBPLOT.
If we wish to plot discrete points, using + as a symbol, we can use the following
10
Module 1. MATLAB
plot(x,z,'+')
30 25 20 z 15 10 5 0 2 4 6 x 8 10 12 Text can be added directly to a figure using the gtext command.
gtext('string') displays the graph window, puts up a cross-hair, and waits for a mouse
button or keyboard key to be pressed. The cross-hair can be positioned with the mouse. Pressing a mouse button or any key writes the text string onto the graph at the selected location. Consider now the following equation y(t) = 4 e-0.1 t we can solve this for a vector of t values by two simple commands
t = 0:1:50; y = 4*exp(-0.1*t);
and we can obtain a plot by typing
plot(t,y)
Notice that we could shorten the sequence of commands by typing
plot(t,4*exp(-0.1*t))
1.7 Plotting
11
4 3 2 1 0 y
10
20 t
30
40
50
10
20 t
30
40
50
axis('square') will place the plot in a square box, while axis('normal') will change back to a normal aspect ratio.
You can also explicitly set the upper and lower bounds on the plot with
12
Module 1. MATLAB
v = [0 50 0 4]; axis(v);
Multiple curves can be placed on the same plot in the following fashion.
plot(t,4*exp(-0.1*t),t,t.*exp(-0.1*t),'--')
4
10
20
30
40
50
10
20
30
40
50
10
20
30
40
50
13
v = [x',z'] v= 1 3 5 7 9 11 5 10 15 20 25 30
v(:,1) ans = 1 3 5 7 9 11
If we wished to look at the second column of v, we could use
v(:,2) ans = 5 10 15 20 25 30
And we can construct the same plot as before, by using ('--' gives a dotted line)
plot(v(:,1),v(:,2),'--')
14
Module 1. MATLAB
30 column 2 of v 25 20 15 10 5 0 2 4 6 8 column 1 of v 10 12
t = 0:0.01:50; y = sin(t);
since the computation time for this method is over 200 times faster than the non-vectorized methods.
1.10
m-files
1.10 m-files
15
Thus far we have shown the interactive features of MATLAB, by entering one command at a time. One reason that MATLAB is powerful is that it is a language, and programs of MATLAB code can be saved for later use. There are two ways of generating your own MATLAB code: (1) script files and (2) function routines. 1.10.1 Script files
A script file is simply a sequence of commands that could have been entered interactively. When the sequence is long, or must be performed a number of times it is much easier to generate a script file. The following example is for the quadratic map population growth model xk+1 = xk (1 xk) where xk represents the value of the population (dimensionless) at the kth time step. We have titled the file popmod.m and stored it in our directory. The file is run by simply typing popmod in the MATLAB command window.
% popmod.m % population model, script file example % clear x,k n = input('input final time step '); alpha = input('input alpha '); xinit = input('input initial population '); x(1) = xinit; time(1)= 0; for k = 2:n+1; time(k) = k-1; x(k) = alpha*x(k-1)*(1-x(k-1)); end plot(time,x) % end of script file example
Notice that we have used the MATLAB input function to prompt the user for data. Also note that a percent sign (%) may be used to put comments in a script or function file. Any text after a % is ignored. 1.10.2 Function routines
A more powerful way of solving problems is to write MATLAB function routines. Function routines are similar to subroutines in FORTRAN. Consider the previous example.
16
Module 1. MATLAB
% 29 August 1993 by Professor Bequette clear time; clear x; clear k; x(1) = xinit; time(1)= 0; for k = 2:n+1; time(k) = k-1; x(k) = alpha*x(k-1)*(1-x(k-1)); end % end of function file example
we can now "run" this function routine (using alpha = 2.8, xinit = 0.1, n = 30) by typing
[tstep,xpop]=pmod(2.8,0.1,30); plot(tstep,xpop)
0.7 0.6 0.5 xpop 0.4 0.3 0.2 0.1 0 5 10 15 tstep 20 25 30
This function routine can also be called by other function routines. This feature leads to "structured programming"; structured programs are easy to follow and debug. MATLAB has many built-in function routines that you will use throughout this course.
1.11
Diary
When preparing homework solutions it is often necessary to save the sequence of commands and output results in a file to be turned in with the homework. The diary command allows this.
diary file_name causes a copy of all subsequent terminal input and most of the resulting output to be written on the file named file_name. diary off suspends it. diary on turns it back on. diary, by itself, toggles the diary state. Diary files may be edited later with a
text editor to add comments or remove mistaken entries.
1.11 Diary
17
Often the consultants (or TA) wish to see a diary file of your session to assist them in troubleshooting your MATLAB problems.
1 . 1 2 Toolboxes
MATLAB Toolboxes are a collection of function routines written to solve specialized problems. The Signals and Systems Toolbox is distributed with the Student Edition of MATLAB. The newest edition of Student MATLAB also contains the Symbolic Algebra toolbox, which is a collection of routines that allows one to obtain analytical solutions to algebraic and differential calculus problems, similar to MAPLE. One toolbox used frequently in the chemical process control course is the Control Systems Toolbox.
1 . 1 4 Contacting MATHWORKS
MATHWORKS has a homepage on the World Wide Web. The URL for this homepage is: http://www.mathworks.com/ You can find answers to frequently asked questions (FAQ) on this homepage. Also, there are a number of technical notes which give more information on using MATLAB function routines. Suggestions are made for modifying these routines for specific problems. There is also a MATLAB newsgroup (bulletin board) which has up-to-date questions (usually supplied by MATLAB users) and answers (supplied by other users as well as MATHWORKS personnel). The newgroup is: comp.soft-sys.matlab Before posting questions on this newsgroup it is a good idea to read the FAQ from the MATHWORKS.
18
Module 1. MATLAB
clear clc diary end exp for format function gtext help hold i f length lookfor plot size subplot who whos * ' ; . * . / :
removes all variables from workspace clears command window save the text of a MATLAB session end of loop exponential function generates loop structure output display format user generated function place text on a plot holds current plot and allows new plot to be placed on current plot conditional test length of a vector keyword search on help variables plots vectors size of the array multiple plots in a figure window view variables in workspace view variables in workspace, with more detail (size, etc.) matrix multiplication transpose suppress printing (also - end of row, when used in matrices) element by element multplication element by element division denotes a column in a matrix or creates a vector
Practice Exercises
1. Plot the following three curves on (i) a single plot and (ii) multiple plots (using the subplot command): 2 cos(t), sin(t) and cos(t)+sin(t). Use a time period such that 2 or 3 peaks occur for each curve. Use solid, dashed, and '+' symbols for the different curves. Use roughly 25-50 points for each curve. 2. a. Calculate the rank, determinant and matrix inverse of the following matrices (use help rank, help det and help inv) A = 1 1 2 2 2 4 1 1 2
Practice Exercises 1 1 2 1 1 2 2 4 4 2 4 4 1 1 2 1 1 5
19
3.
4.
1 1 1 0
0 2 3 0
0 0 1 0
2 6 8 2
Q solve for R.
11.896 17.192
7. Find the solutions to the equation f(x) = 3x3 + x2 + 5x 6 = 0. Use roots and fzero.
Module 1. MATLAB
with the initial condition x1(0) = x2(0) = 1. Use ode5 and plot your results.
9. Write your own function file for the following equation k(T) = c a exp(b T ln dT e T + f T2)
for a = 3.33, b = 13.148, c = 5639.5, d = 1.077, e = 5.44x10-4, f = 1.125x10-7 T is in units of Kelvin Plot k as a function of T for temperatures from 373 to 600 K. (we suggest 50 points) ^ cm3 10. Find V ( ) for the following equation of state gmol RT a P = ^ ^ (V + b ) V b T0.5V ^ for P = 13.76 bar, b = 44.891 constant in appropriate units. cm3 cm 6 bar , T = 333 K, a = 1.56414x108 , R = ideal gas gmol gmol 2 K 0.5