Академический Документы
Профессиональный Документы
Культура Документы
1 Introduction
In this course, we will make frequent use of the MathWorks software package MATLAB.
1
1.2 The MATLAB Interface
The default MATLAB screen is divided into four windows.
The following is a list of some elementary quantities and functions used in MATLAB:
√π pi
−1 i
|x| abs(x)
√
x sqrt(x)
ex exp(x)
ln(x) log(x)
sin(x) sin(x)
cos(x) cos(x)
tan(x) tan(x)
sin−1 (x) asin(x)
cos−1 (x) acos(x)
tan−1 (x) atan(x)
A full list of elementary functions can be found in the MATLAB help menu.
(a) |2π 3 − 5|
√
(b) π 2 − 1
(c) e3 ln(2)
2 π
(d) sin + sec(3)
3
2
1.4 Formatting Numerical Output in MATLAB
By default, MATLAB displays all numerical output using four decimal places. If further
accuracy is needed, then additional decimal places can be displayed.
3
This creates a text file Script1.txt in the current directory (which can be identified in the
current directory window) which records the commands that follow, along with MATLAB’s
responses, until the command diary off is entered.
To print the text file Script.txt, follow the xprint instructions posted in the Blocker lab. That
is, open a terminal window by clicking the terminal icon from the bottom of your screen and
enter the following command:
You will be prompted to give your NetID and password. The file will be printed in Blocker
130.
4
2 Vectors and Matrices
2.1 Vectors
Column and row vectors can be created in MATLAB by using square brackets. To create a
column vector, enclose a set of numbers in square brackets and use a semicolon to delimit the
numbers. For example, to create a column vector with three elements, enter the command:
>> x=[1;2;3]
To create a row vector, enclose a set of numbers in square brackets and use a space or comma
to delimit the numbers:
>> v=[1 2 3]
>> w=[4,5,6]
x = [x1 : p : xn ].
>> x=[0:2:10]
It is also possible to create a vector of uniformly spaced elements with a negative increment.
To create a list of numbers from 100 to 80 decreasing by 5, enter the command:
>> z=[100:-5:80]
The linspace command can also be used to create a vector with uniformly spaced elements.
In particular, the command linspace(a,b,n) creates a vector of n regularly spaced elements
between a and b. As an example, enter the following commands:
>> linspace(1,10,10)
>> linspace(1,10,4)
This technique will be used for plotting the graph of a function. For example, we can create
a set of points on the graph of the function y = ex using the commands:
>> x=[0:0.1:1];
>> y=exp(x);
5
2.3 Characterizing a Vector
The length command returns the number of elements in a vector.
The max and min commands return the maximum and minimum elements of a vector.
>> M=sqrt(dot(a,a))
2.5 Matrices
To create a matrix in MATLAB, we enter the elements of each row delimited by a space,
and use semicolons to mark the end of each row.
>> A=[1 2; 3 4]
>> B=[1 2 3; 4 5 6; 7 8 9]
There are commands in MATLAB which make creating certain types of matrices easier.
6
As an example, enter the following in the command window:
>> zeros(2)
>> zeros(2,3)
>> ones(2)
>> ones(3,2)
>> A=ones(2);
>> B=[1 2; 3 4];
>> A*B
>> B∧2
7
Componentwise multiplication and exponentiation are performed by using the “dot” nota-
tion for the commands .* or .^.
>> A.*B
>> B.∧2
>> X=[1 2 3; 1 1 1]
>> X’
The command A/B evaluates the expression AB −1 , while the command A./B performs com-
ponentwise division of A and B.
>> A/B
>> A./B
To evaluate the determinant of a square matrix, we use the command det. Provided that a
square matrix is nonsingular, we can evaluate its inverse using the command inv.
>> det(A)
>> inv(A)
The eigenvalues of a square matrix can be computed using the command eigs.
>> eigs(A)
8
3 Plotting and Graphics
3.1 Basic Plotting
3.1.1 The Plot Command
To plot a function in MATLAB, we use the plot command.
First we define the domain of interest and desired step size, say 0.1.
>> x=0:0.1:10;
>> y=cos(x);
>> plot(x,y)
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
0 2 4 6 8 10
To label the axes of a plot, we use the xlabel and ylabel commands.
>> xlabel(’x’)
>> ylabel(’cos(x)’)
9
Cosine Plot
1
0.8
0.6
0.4
0.2
cos(x)
0
-0.2
-0.4
-0.6
-0.8
-1
0 2 4 6 8 10
x
>> t=0:0.01:4;
>> f=exp(-t)*sin(t);
Since exp(-t) and sin(t) are row vectors of the same size, they cannot be multiplied using
matrix multiplication. How do we get around this error?
One way is to use the ezplot command which defines the function and its domain in one
command:
>> ezplot(’exp(-t)*sin(t)’,[0,4])
>> xlabel(’t’)
>> ylabel(’f(t)’)
0.35
0.3
0.25
0.2
f(t)
0.15
0.1
0.05
-0.05
0 0.5 1 1.5 2 2.5 3 3.5 4
t
10
Alternatively, we could use the .* command for componentwise multiplication of vectors.
That is:
>> t=0:0.01:4;
>> f=exp(-t).*sin(t);
>> plot(t,f)
>> xlabel(’t’)
>> ylabel(’f(t)’)
Example: Suppose we want to plot the functions f (t) = e−t and g(t) = e−2t over 0 ≤ t ≤ 5.
>> t=0:0.01:5;
>> f=exp(-t);
>> g=exp(-2*t);
>> plot(t,f,t,g)
>> xlabel(’t’)
>> ylabel(’f(t), g(t)’)
>> title(’Multiplot’)
Multiplot
1
0.9
0.8
0.7
0.6
f(t), g(t)
0.5
0.4
0.3
0.2
0.1
0
0 1 2 3 4 5
t
Note that MATLAB uses two different colors to differentiate between the two curves.
11
3.2.2 Setting Colors and Line Style
The color and line style of each curve can be manually selected using the plot command.
The color is specified in the plot command immediately after the function is specified by
enclosing the appropriate letter assigned to each color in single quotes. Similarly, the line
style is specified by enclosing the appropriate symbol assigned to each line style in single
quotes.
Example: Suppose we want to plot the functions f (x) = sin(x) and g(x) = cos(x) over
0 ≤ x ≤ 5. Additionally, we would like the graph of f to be a solid red line and the graph
of g to be a dashed blue line. Starting in the usual way, we have:
>> x=0:0.01:5;
>> f=sin(x);
>> g=cos(x);
>> plot(x,f,’r’,x,g,’b--’)
>> xlabel(’x’)
>> ylabel(’sin(x), cos(x)’)
0.8
0.6
0.4
0.2
sin(x), cos(x)
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5
x
The following is a list of some colors and line styles available in MATLAB.
Color/Line Style Specifier
Black k
Blue b
Red r
Green g
Yellow y
Cyan c
Magenta m
Solid Line -
Dashed Line --
Dotted Line :
Dash-Dotted Line -.
A full list of available colors and line styles can be found in the MATLAB help menu.
12
3.2.3 Adding Legends
A legend can be added to the plot of multiple functions using the legend command.
To add a legend to our previous plot of f (x) = sin(x) and g(x) = cos(x), enter the command:
>> legend(sin(x),cos(x))
1
sin(x)
0.8 cos(x)
0.6
0.4
0.2
sin(x), cos(x)
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5
x
Example: Consider the parametric curve defined by x(t) = sin(t), y(t) = t cos(t) for 0 ≤ t ≤
2π. Suppose we want to plot both x(t) and y(t) as functions of t and also want to plot the
curve in the xy-plane.
>> t=0:0.01:2*pi;
>> x=sin(t);
>> y=t.*cos(t);
>> subplot(1,2,1)
>> plot(t,x,’r’,t,y,’b’)
>> xlabel(’t’)
>> ylabel(’x(t), y(t)’)
>> legend(’x(t)’,’y(t)’)
>> subplot(1,2,2)
>> plot(x,y)
>> xlabel(’x’) ylabel(’y’)
13
8 8
x(t)
6 y(t) 6
4 4
2 2
0 0
x(t), y(t)
y
-2 -2
-4 -4
-6 -6
-8 -8
-10 -10
0 5 10 -1 0 1
t x
14
4 Symbolic Calculations in MATLAB
4.1 Defining Symbolic Variables and Expressions
Symbolic variables can be defined in MATLAB using the syms command. The symbolic
variables we have defined appear in the Workspace window.
>> syms a b c x
>> y=a*x∧2+b*x+c;
Symbolic variables can be cleared using the clear command. In particular, if x is defined as a
symbolic variable, then the command clear x will delete the variable x. To clear all variables
from the Workspace window at once, enter the command clear.
>> syms x
>> y=(x+2)*(x-4);
>> expand(y)
>> syms x y
>> z=exp(x+y);
>> expand(z)
>> syms x y
>> f=sin(x+y);
>> expand(f)
15
4.2.2 The Collect Command
The collect command groups all terms that have a variable to the same power.
Example: Suppose we want to group the equation y = x(x2 + sin x)(x3 + ex ) by powers of x.
>> syms x
>> y=x*(x∧2+sin(x))*(x∧3+exp(x));
>> collect(y)
>> syms x y
>> collect(x∧2y+x*y-x∧2-2*x,x)
>> syms x
>> factor(x∧4-1)
x4 − 81
Example: Simplify the expression y = .
x2 − 9
>> syms x
>> y=(x∧4-81)/(x∧2-9);
>> simplify(y)
>> syms x y c
>> f=exp(c*log(sqrt(x∧2+y∧2)));
>> simplify(f)
16
Example: Use the simplify command to show that sin2 x + cos2 x = 1.
>> syms x
>> simplify(sin(x)∧2+cos(x)∧2)
x2 − 8x + 15 = 0.
>> syms x
>> y=x∧2-8*x+15;
>> solve(y)
ax2 + bx + c = 0.
>> syms x a b c
>> y=a*x∧2+b*x+c;
>> solve(y)
Example: Suppose we want to solve the following equation for the variable y
ex y + cos(x) = 1.
>> syms x y
>> solve(exp(x)*y+cos(x)-1,y)
It is not necessary to define symbolic variables to solve an equation. We can simply use the
syntax solve(’eqn’).
>> solve(’x∧2-6*x-12’)
17
The solve command can also be used to solve systems of equations.
5x + 4y = 3
x − 6y = 2.
>> s=solve(’5*x+4*y=3’,’x-6*y=2’)
>> x=s.x
>> y=s.y
>> s=solve(’x∧3+2*x-1’)
>> eval(s)
>> double(s)
Example: Suppose we want to symbolically define the function f (t) = eat and evaluate this
function for t = 0, 1, 2, . . ..
>> syms a t
>> f=exp(a*t);
>> subs(f,t,0)
>> subs(f,t,1)
>> subs(f,t,2)
18
Multiple substitutions can be made at the same time.
Example: Suppose we want to symbolically define the function f (x, y) = sin(x) + cos(y) and
evaluate this function for x = 1 and y = 2.
>> syms x y
>> f=sin(x)+cos(y);
>> subs(f,{x,y},{1,2})
19
5 Basic Calculus in MATLAB
5.1 Limits
Limits can be calculated in MATLAB by using the limit command. To compute limits of
the form lim f (x), we use the syntax limit(f,a).
x→a
√
Example: Find the limit of f (x) = x3 + 1 as x approaches 2.
>> syms x
>> f=sqrt(x∧3+1);
>> limit(f,2)
To compute limits of the form lim f (x), we use the syntax limit(f,inf ) or limit(f,-inf ).
x→±∞
√
Example: Evaluate lim x2 + x − x .
x→∞
>> syms x
>> f=sqrt(x∧2+x)-x;
>> limit(g,inf)
√
4x2 − x + 1
Example: Evaluate lim .
x→−∞ x+7
>> syms x
>> f=(4*x∧2+1)/(x+7);
>> limit(f,-inf)
x
Example: Show that lim does not exist.
x→0 |x|
>> syms x
>> f=x/abs(x);
>> L=limit(f,x,0,’left’)
>> R=limit(f,x,0,’right’)
Since L 6= R, the limit does not exist.
20
5.2 Derivatives
Derivatives can be computed using the diff command. To find the derivative of a function
of one variable f (x), we use the syntax diff(f ).
>> syms x
>> f=sin(5*x);
>> diff(f)
To compute higher derivatives of a function, f (n) (x), we use the syntax diff(f,n).
>> syms t
>> f=t*exp(-3*t);
>> diff(f,2)
To find the derivative of a function of two or more variables f (x, y), we use the syntax
diff(f,x) or diff(f,y).
Example: Find the first and second-order partial derivatives of g(x, y) = sin(xy) + ex+y .
>> syms x y
>> g=sin(x*y)+exp(x+y)
>> gx=diff(g,x)
>> gy=diff(g,y)
>> gxx=diff(gx,x)
>> gyy=diff(gy,y)
>> gxy=diff(gx,y)
>> gyx=diff(gy,x)
21
5.3 Integration
Integrals
R can be computed using the int command. To evaluate indefinite integrals of the
form f (x)dx, we use the syntax int(f ).
Z
Example: Evaluate ln xdx.
>> syms x
>> f=log(x);
>> int(f)
Z b
To evaluate definite integrals of the form f (x)dx, we use the syntax int(f,a,b).
a
Z 4
Example: Evaluate | sin(x) + x|dx.
1
>> syms x
>> f=abs(sin(x)+x);
>> int(f,1,4)
In some cases, we need to tell MATLAB to integrate with respect to a particular variable.
This can be done using the syntax int(f,x).
Z Z
Example: Evaluate 2x sec(y)dx and 2x sec(y)dy.
>> syms x y
>> f=2*x*sec(y)
>> int(f,x)
>> int(f,y)
Z bZ d
To evaluate multiple integrals such as f (x, y)dydx, we simply nest the int command.
a c
That is, we use the syntax int(int(f,y,c,d),a,b).
Z 2 Z sin(x)
Example: Evaluate exy dydx.
1 0
>> syms x y
>> int(int(f,y,0,sin(x)),1,2)
22
5.4 Sums and Products
Sums can be computed using the sum command.
5
X
Example: Evaluate the sum k.
k=1
>> a=1:5;
>> sum(a)
10
Y
Example: Evaluate the product ln(k).
k=1
>> a=1:10;
>> prod(log(a))
>> syms k n
>> symsum(1/k-1/(k+1),1,n)
23
6 M-Files
The ability to write M-files is necessary for this course.
Let us write a script M-file to plot the function f (x) = sin(x) on the interval [−2π, 2π]. In
the editor window, enter the following commands:
% Your Name
% Math 442 - Mathematical Modeling
x=-2*pi:0.01:2*pi;
f=sin(x);
plot(x,f)
To save this file, click the “Save” icon in the upper left corner of the MATLAB window and
choose “Save As”. Save your M-file as SinePlot.m. To run this script M-file, click the “Run”
icon (looks like a green arrow) at the top of the MATLAB window. MATLAB goes through
your M-file line by line and executes each command.
Let us write a function M-file to find the derivative of f (x) = cos(x) at a given value of
x ∈ R. In the editor window, enter the following commands:
% Your Name
% Math 442 - Mathematical Modeling
function CosineDiff(n)
syms x
f=cos(x);
f1=diff(f,x);
subs(f1,x,n)
24
Every function M-file begins with the function command, and the input is placed in paren-
theses after the name of the function M-file. To save this file, click the “Save” icon in
the upper left corner of the MATLAB window and choose “Save As”. Save your M-file as
CosineDiff.m. For every function M-file, the file name must be the same as the name of the
function. To run this function M-file, enter the following command in the command window:
>> CosineDiff(0)
The function M-file takes the input n = 0, computes the derivative of cos(x) at x = 0, and
returns the answer in the command window.
Function M-files can also take several inputs at once using the syntax
function Name(x,y,z,...).
Z b
Let us write a function M-file to evaluate the definite integral cos(x)dx for given values
a
of a and b. Open a new editor window and enter the following commands:
% Your Name
% Math 442 - Mathematical Modeling
function CosineInt(a,b)
syms x
f=cos(x);
int(f,a,b)
Z 2π
To evaluate the integral cos(x)dx, enter the following command in the command window:
0
>> CosineInt(0,2*pi)
25
7 Programming in MATLAB
It is possible to create your own programs in MATLAB using an M-file. If you are familiar
with C or C++, you will find programming in MATLAB to be similar.
7.1 Loops
7.1.1 The For Loop
A for loop can be used to repeat a sequence of calculations a predetermined number of times.
Let us write a program which uses a for loop to compute the sum of the first n integers.
Start by opening a new script M-file and entering the following commands.
% Your Name
% Math 442 - Mathematical Modeling
Save this script M-file as IntegerSum.m and run the script to see your final answer.
The index of the for loop can be set to something other than 1. For example, the syntax for
k=2:2:100 counts from 2 to 100 by increments of 2.
Let us write a program which uses a while loop to list the integers from 1 to n. Open a new
script M-file and enter the following commands.
26
% Your Name
% Math 442 - Mathematical Modeling
Save this script M-file as IntegerList.m and run the script to view the output.
7.2 Branching
Branching refers to a program performing different operations for different cases.
if x<y
z=1;
elseif x>y
z=2;
else
z=3;
end
If x < y, then the variable z is assigned the value 1. Similarly, if x > y, then z = 2, and if
x = y, then z = 3.
27
Consider the following example:
switch x
case 1
y=1;
case 3
y=2;
case 5
y=3;
end
References
1. P. Howard, MATLAB 7.8 Basics. http://www.math.tamu.edu/ phoward/
28