











































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Material Type: Notes; Professor: Klein; Class: MATH MODELING; Subject: MATHEMATICS; University: Texas A&M University; Term: Unknown 1989;
Typology: Study notes
1 / 51
This page cannot be seen from the preview
Don't miss anything!












































- Fall P. Howard At the prompt, designated by two arrows, >>, type 2 + 2 and press Enter. You should find that the answer has been assigned to the default variable ans. Next, type 2+2; and hit Enter. Notice that the semicolon suppresses screen output in MATLAB. We will refer to a series of commands as a MATLAB script. For example, we might type
t=4; s=sin(t)
MATLAB will report that s = -.7568. (Notice that MATLAB assumes that t is in radians, not degrees.) Next, type the up arrow key on your keyboard, and notice that the command s=sin(t) comes back up on your screen. Hit the up arrow key again and t=4; will appear at the prompt. Using the down arrow, you can scroll back the other way, giving you a convenient way to bring up old commands without retyping them. (The left and right arrow keys will move the cursor left and right along the current line.) Occasionally, you will find that an expression you are typing is getting inconveniently long and needs to be continued to the next line. You can accomplish this by putting in three dots and typing Enter. Try the following:^1
2+3+4+... +5+ ans = 20
Notice that 2+3+4+... was typed at the Command Window prompt, followed by Enter. When you do this, MATLAB will proceed to the next line, but it will not offer a new prompt. This means that it is waiting for you to finish the line you’re working on.
MATLAB uses double-precision floating point arithmetic, accurate to approximately 15 dig- its. By default, only a certain number of these digits are shown, typically five. To display more digits, type format long at the beginning of a session. All subsequent numerical output will show the greater precision. Type format short to return to shorter display. MATLAB’s four basic data types are floating point (which we’ve just been discussing), symbolic (see Section 2), character string, and inline function. A list of all active variables—along with size and type—is given in the Workspace. Ob- serve the differences, for example, in the descriptions given for each of the following variables.
t=5; v=1:25; s=’howdy’ y=solve(’a*y=b’) (^1) In the MATLAB examples of these notes, you can separate the commands I’ve typed in from MATLAB’s
responses by picking out those lines that begin with the command line prompt, >>.
For many of the assignments this semester, and also for the projects, you will need to turn in a log of MATLAB commands typed and of MATLAB’s responses. This is straightforward in MATLAB with the diary command.
Example 1.1. Write a MATLAB script that sets x = 1 and computes tan−^1 x (or arctan x). Save the script to a file called script1.txt and print it. In order to accomplish this, we use the following MATLAB commands.
diary script1.txt x= x = 1 atan(1) ans =
diary off
In this script, the command diary script1.txt creates the file script1.txt, and MATLAB begins recording the commands that follow, along with MATLAB’s responses. When the command diary off is typed, MATLAB writes the commands and responses to the file script1.txt. Commands typed after the diary off command will no longer be recorded, but the file script1.txt can be reopened either with the command diary on or with diary script1.txt. Finally, the diary file script1.txt can be deleted with the command delete script1.txt. In order to print script1.txt, follow the xprint instructions posted in the Blocker lab. More precisely, open a terminal window by selecting the terminal icon from the bottom of your screen and use the xprint command
xprint -d blocker script1.txt
You will be prompted to give your NetID (neo account ID) and password. The file will be printed in Blocker 133. △
The Command Window can be cleared with the command clc, which leaves your variable definitions in place. You can delete your variable definitions with the command clear. All variables in a MATLAB session can be saved with the menu option File, Save Workspace As, which will allow you to save your workspace as a .mat file. Later, you can open this file simply by choosing File, Open, and selecting it. A word of warning, though: This does not save every command you have typed into your workspace; it only saves your variable assignments. For bringing all commands from a session back, see the discussion under Command History.
Symbolic manipulations in MATLAB are carried out on symbolic variables, which can be either particular numbers or unspecified variables. The easiest way in which to define a variable as symbolic is with the syms command.
Example 2.1. Suppose we would like to symbolically define the logistic model
R(N) = aN(1 −
where N denotes the number of individuals in a population and R denotes the growth rate of the population. First, we define both the variables and the parameters as symbolic objects, and then we write the equation with standard MATLAB operations:
syms N R a K R=aN(1-N/K) R =
aN(1-N/K)
Here, the expressions preceded by >> have been typed at the command prompt and the others have been returned by MATLAB. △
Symbolic objects can also be defined to take on particular numeric values.
Example 2.2. Suppose that we want a general form for the logistic model, but we know that the carrying capacity K is 10, and we want to specify this. We can use the following commands:
K=sym(10) K = 10 R=aN(1-N/K) R = aN(1-1/10*N)
2.1.1 Complex Numbers
You can also define and manipulate symbolic complex numbers in MATLAB.
Example 2.3. Suppose we would like to define the complex number z = x + iy and compute z^2 and z¯z. We use
syms x y real z=x+iy z = x+iy square=expand(zˆ2)
square = xˆ2+2ix*y-yˆ
zzbar=expand(z*conj(z)) zzbar = xˆ2+yˆ
Here, we have particularly specified that x and y be real, as is consistent with complex notation. The built-in MATLAB command conj computes the complex conjugate of its input, and the expand command is required in order to force MATLAB to multiply out the expressions. (The expand command is discussed more below in Subsubsection 2.2.2.)
2.1.2 The Clear Command
You can clear variable definitions with the clear command. For example, if x is defined as a symbolic variable, you can type clear x at the MATLAB prompt, and this definition will be removed. (Clear will also clear other MATLAB data types.) If you have set a symbolic variable to be real, you will additionally need to use syms x unreal or the Maple kernel that MATLAB calls will still consider the variable real.
Once an expression has been defined symbolically, MATLAB can manipulate it in various ways.
2.2.1 The Collect Command
The collect command gathers all terms together that have a variable to the same power.
Example 2.4. Suppose that we would like organize the expression
f (x) = x(sin x + x^3 )(ex^ + x^2 )
by powers of x. We use
syms x f=x(sin(x)+xˆ3)(exp(x)+xˆ2) f = x(sin(x)+xˆ3)(exp(x)+xˆ2) collect(f) ans = xˆ6+exp(x)xˆ4+sin(x)xˆ3+sin(x)exp(x)x
△
2.2.4 The Horner Command
The horner command is useful in preparing an expression for repeated numerical evaluation. In particular, it puts the expression in a form that requires the least number of arithmetic operations to evaluate.
Example 2.7. Re-write the polynomial from Example 6 in Horner form.
syms x f=xˆ4-2xˆ2+ f = xˆ4-2xˆ2+ horner(f) ans = 1+(-2+xˆ2)*xˆ
2.2.5 The Simple Command
The simple command takes a symbolic expression and re-writes it with the least possible number of characters. (It runs through MATLAB’s various manipulation programs such as collect, expand, and factor and returns the result of these that has the least possible number of characters.)
Example 2.8. Suppose we would like a reduced expression for the function
f (x) = (1 +
x
x^2
)(1 + x + x^2 ).
We use
syms x f f=(1+1/x+1/xˆ2)(1+x+xˆ2) f = (1+1/x+1/xˆ2)(x+1+xˆ2) simple(f) simplify: (x+1+xˆ2)ˆ2/xˆ radsimp: (x+1+xˆ2)ˆ2/xˆ combine(trig): (3xˆ2+2x+2xˆ3+1+xˆ4)/xˆ factor: (x+1+xˆ2)ˆ2/xˆ expand: 2x+3+xˆ2+2/x+1/xˆ combine: (1+1/x+1/xˆ2)*(x+1+xˆ2)
convert(exp): (1+1/x+1/xˆ2)(x+1+xˆ2) convert(sincos): (1+1/x+1/xˆ2)(x+1+xˆ2) convert(tan): (1+1/x+1/xˆ2)(x+1+xˆ2) collect(x): 2x+3+xˆ2+2/x+1/xˆ mwcos2sin: (1+1/x+1/xˆ2)*(x+1+xˆ2) ans = (x+1+xˆ2)ˆ2/xˆ
In this example, three lines have been typed, and the rest is MATLAB output as it tries various possibilities. In returns the expression in ans, in this case from the factor command. △
2.2.6 The Pretty Command
MATLAB’s pretty command simply re-writes a symbolic expression in a form that appears more like typeset mathematics than does MATLAB syntax.
Example 2.9. Suppose we would like to re-write the expression from Example 3.8 in a more readable format. Assuming, we have already defined f as in Example 3.8, we use pretty(f) at the MATLAB prompt. (The output of this command doesn’t translate well into a printed document, so I won’t give it here.)
MATLAB’s built-in function for solving equations symbolically is solve.
Example 2.10. Suppose we would like to solve the quadratic equation
ax^2 + bx + c = 0.
We use
syms a b c x eqn=axˆ2+bx+c eqn = axˆ2+bx+c roots=solve(eqn) roots = 1/2/a(-b+(bˆ2-4ac)ˆ(1/2)) 1/2/a(-b-(bˆ2-4ac)ˆ(1/2))
prey = 0 1/dc pred = 0 1/ba
Again, MATLAB knows to set each of the expression Rx and Ry to 0. In this case, MAT- LAB has returned two solutions, one with (0, 0) and one with ( (^) dc , a b ). In this example, the appearance of [prey pred] particularly requests that MATLAB return its solution as a vector with two components. Alternatively, we have the following:
pops=solve(Rx,Ry) pops = x: [2x1 sym] y: [2x1 sym] pops.x ans = 0 1/dc pops.y ans = 0 1/ba
In this case, MATLAB has returned its solution as a MATLAB structure, which is a data array that can store a combination of different data types: symbolic variables, numeric values, strings etc. In order to access the value in a structure, the format is
structure name.variable identification △
In many cases, we would like to combine symbolic manipulation with numerical calculation.
2.4.1 The Double and Eval commands
The double and eval commands change a symbolic variable into an appropriate double vari- able (i.e., a numeric value).
Example 2.12. Suppose we would like to symbolically solve the equation x^3 + 2x − 1 = 0, and then evaluate the result numerically. We use
syms x r=solve(xˆ3+2*x-1); eval(r) ans =
-0.2267 + 1.4677i -0.2267 - 1.4677i
double(r) ans =
-0.2267 + 1.4677i -0.2267 - 1.4677i
MATLAB’s symbolic expression for r is long, so I haven’t included it here, but you should take a look at it by leaving the semicolon off the solve line. △
2.4.2 The Subs Command
In any symbolic expression, values can be substituted for symbolic variables with the subs command.
Example 2.13. Suppose that in our logistic model
R(N) = aN(1 −
we would like to substitute the values a = .1 and K = 10. We use
syms a K N R=aN(1-N/K) R = aN(1-N/K) R=subs(R,a,.1) R = 1/10N(1-N/K) R=subs(R,K,10) R = 1/10N(1-1/10*N)
Alternatively, numeric values can be substitued in. We can accomplish the same result as above with the commands
syms a K N R=aN(1-N/K) R = aN(1-N/K) a=.
In MATLAB it’s particularly easy to decorate a plot. For example, minimize your plot by clicking on the left button on the upper right corner of your window, then add the following lines in the Command Window:
xlabel(’Here is a label for the x-axis’) ylabel(’Here is a label for the y-axis’) title(’Useless Plot’) axis([0 4 2 10])
The only command here that needs explanation is the last. It simply tells MATLAB to plot the x-axis from 0 to 4, and the y-axis from 2 to 10. If you now click on the plot’s button at the bottom of the screen, you will get the labeled figure, Figure 2.
(^20) 0.5 1 1.5 2 2.5 3 3.5 4
3
4
5
6
7
8
9
10
Here is a label for the x−axis
Here is a label for the y−axis
Useless Plot
Useless line
Figure 2: A still pretty much ridiculously simple linear plot.
I added the legend after the graph was printed, using the menu options. Notice that all this labeling can be carried out and edited from these menu options. After experimenting a little, your plots will be looking great (or at least better than the default-setting figures displayed here). Not only can you label and detail your plots, you can write and draw on them directly from the MATLAB window. One warning: If you retype plot(x,y) after labeling, MATLAB will think you want to start over and will give you a clear figure with nothing except the line. To get your labeling back, use the up arrow key to scroll back through your commands and re-issue them at the command prompt. (Unless you labeled your plots using menu options, in which case you’re out of luck, though this might be a good time to consult Section 3.6 on saving plots.) △ Defining vectors as in the example above can be tedious if the vector has many compo- nents, so MATLAB has a number of ways to shorten your work. For example, you might try:
X=1: X = 1 2 3 4 5 6 7 8 9 X=0:2: X = 0 2 4 6 8 10
In order to plot a function with the plot command, we proceed by evaluating the function at a number of x-values x 1 , x 2 , ..., xn and drawing a curve that passes through the points {(xk, yk)}nk=1, where yk = f (xk).
Example 3.2. Use the plot command to plot the function f (x) = x^2 for x ∈ [0, 1]. First, we will partition the interval [0,1] into twenty evenly spaced points with the com- mand, linspace(0, 1, 20). (The command linspace(a,b,n) defines a vector with n evenly spaced points, beginning with left endpoint a and terminating with right endpoint b.) Then at each point, we will define f to be x^2. We have
x=linspace(0,1,20) x = Columns 1 through 8 0 0.0526 0.1053 0.1579 0.2105 0.2632 0.3158 0. Columns 9 through 16 0.4211 0.4737 0.5263 0.5789 0.6316 0.6842 0.7368 0. Columns 17 through 20 0.8421 0.8947 0.9474 1. f=x.ˆ f = Columns 1 through 8 0 0.0028 0.0111 0.0249 0.0443 0.0693 0.0997 0. Columns 9 through 16 0.1773 0.2244 0.2770 0.3352 0.3989 0.4681 0.5429 0. Columns 17 through 20 0.7091 0.8006 0.8975 1. plot(x,f)
Only three commands have been typed; MATLAB has done the rest. One thing you should pay close attention to is the line f=x.ˆ2, where we have used the array operation .ˆ. This operation .ˆ signifies that the vector x is not to be squared (a dot product, yielding a scalar), but rather that each component of x is to be squared and the result is to be defined as a component of f , another vector. Similar commands are .* and ./. These are referred to as array operations, and you will need to become comfortable with their use. △
Example 3.3. In our section on symbolic algebra, we encountered the logistic population model, which relates the number of individuals in a population N with the rate of growth of the population R through the relationship
R(N) = aN(1 −
a K
N^2 + aN.
Taking a = 1 and K = 10, we have
R(N) = −. 1 N^2 + N.
In order to plot this for populations between 0 and 20, we use the following MATLAB code, which creates Figure 3.
(^01) 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2
1
2
3
Figure 4: Plot of x(t) = t^2 + 1 and y(t) = et^ for t ∈ [− 1 , 1].
Example 3.5. For the functions x(t) = t^2 + 1 and y(t) = et, plot x(t) and y(t) on the same figure, both versus t. The easiest way to accomplish this is with the single command
plot(t,x,t,y);
The color and style of the graphs can be specified in single quotes directly after the pair of values. For example, if we would like the plot of x(t) to be red, and the plot of y(t) to be green and dashed, we would use
plot(t,x,’r’,t,y,’g–’)
For more information on the various options, type help plot. Another way to accomplish this same thing is through the hold on command. After typing hold on, further plots will be typed one over the other until the command hold off is typed. For example,
plot(t,x)^2 hold on plot (t,y) title(’One plot over the other’) u=[-1 0 1]; v=[1 0 -1] plot(u,v)
△ (^2) If a plot window pops up here, minimize it and bring it back up at the end.
Often, we will want MATLAB to draw two or more plots at the same time so that we can compare the behavior of various functions.
Example 3.6. Plot the three functions f (x) = x, g(x) = x^2 , and h(x) = x^3. The following sequence of commands produces the plot given in Figure 5.
x = linspace(0,1,20); f = x; g = x.ˆ2; h = x.ˆ3; subplot(3,1,1); plot(x,f); subplot(3,1,2); plot(x,g); subplot(3,1,3); plot(x,h);
(^00) 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
1
(^00) 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
1
(^00) 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
1
Figure 5: Algebraic functions on parade.
The only new command here is subplot(m,n,p). This command creates m rows and n columns of graphs and places the current figure in position p (counted left to right, top to bottom).
In most of our plotting for M151, we will use the plot command, but another option is the built-in function ezplot, which can be used along with symbolic variables.
Example 3.7. Plot the function
f (x) = x^4 + 2x^3 − 7 x^2.
We can use