Professional Documents
Culture Documents
Ch2b - Starting With MATLAB
Ch2b - Starting With MATLAB
to MATLAB ®
MATLAB® has become a powerful tool of technical professionals worldwide. The
term MATLAB is an abbreviation for MATrix LABoratory implying that MATLAB
is a computational tool that employs matrices and vectors/arrays to carry out numeri-
cal analysis, signal processing, and scientific visualization tasks. Because MATLAB
uses matrices as its fundamental building blocks, one can write mathematical
expressions involving matrices just as easily as one would on paper. MATLAB is
available for Macintosh, Unix, and Windows operating systems. A student version of
MATLAB is available for PCs. A copy of MATLAB can be obtained from
The Mathworks, Inc.
3 Apple Hill Drive
Natick, MA 01760-2098
Phone: (508) 647-7000
Website: http://www.mathworks.com
A brief introduction on MATLAB is presented in this appendix. What is presented
is sufficient for solving problems in this book. Other information on MATLAB
required in this book is provided on a chapter-by-chapter basis as needed. Additional
information about MATLAB can be found in MATLAB books and obtained from
the online help. The best way to learn MATLAB is to work with it after one has
learned the basics.
C.1 MATLAB® FUNDAMENTALS
The Command window is the primary area where you interact with MATLAB. A lit-
tle later, we learn how to use the text editor to create M-files, which allow executing
sequences of commands. For now, we focus on how to work in Command window.
We first learn how to use MATLAB as a calculator. We do so by using the algebraic
operators in Table C.1.
To begin to use MATLAB, we use these operators. Type commands to MATLAB
prompt “≫” in the Command window (correct any mistakes by backspacing) and
press the <Enter> key. For example,
≫ a = 2; b = 4; c = −6;
≫ dat = b^2 − 4*a*c
dat =
64
≫ e=sqrt(dat)/10
e =
0.8000
375
376 Appendix C: Introduction to MATLAB®
TABLE C.1
Basic Operations
Operation MATLAB Formula
Addition a+b
Division (right) a/b (means a÷b)
Division (left) a\b (means b÷a)
Multiplication a*b
Power a^b
Subtraction a−b
The first command assigns the values 2, 4, and −6 to the variables a, b, and c,
respectively. MATLAB does not respond because this line ends with a colon. The
second command sets dat to b2 − 4ac and MATLAB returns the answer as 64. Finally,
the third line sets e equal to the square root of dat and divides by 10. MATLAB
prints the answer as 0.8. As function sqrt is used here, other mathematical functions
listed in Table C.2 can be used. Table C.2 provides just a small sample of MATLAB
functions. Others can be obtained from the online help. To get help, type
≫ help
TABLE C.2
Typical Elementary Math Functions
Function Remark
abs(x) Absolute value or complex magnitude of x
acos, acosh(x) Inverse cosine and inverse hyperbolic cosine of x in radians
acot, acoth (x) Inverse cotangent and inverse hyperbolic cotangent of x in radians
angle(x) Phase angle (in radian) of a complex number x
asin, asinh(x) Inverse sine and inverse hyperbolic sine of x in radians
atan, atanh(x) Inverse tangent and inverse hyperbolic tangent of x in radians
conj(x) Complex conjugate of x
cos, cosh(x) Cosine and hyperbolic cosine of x in radian
cot, coth(x) Cotangent and hyperbolic cotangent of x in radian
exp(x) Exponential of x
fix Round toward zero
imag(x) Imaginary part of a complex number x
log (x) Natural logarithm of x
log2(x) Logarithm of x to base 2
log10(x) Common logarithms (base 10) of x
real (x) Real part of a complex number x
sin, sinh(x) Sine and hyperbolic sine of x in radian
sqrt (x) Square root of x
tan, tanh Tangent and hyperbolic tangent of x in radian
Appendix C: Introduction to MATLAB® 377
≫ help log2
a = [1 -3 6 10 -8 11 14];
is a row vector. Defining a matrix is similar to defining a vector. For example, a 3 × 3
matrix can be entered as
A =[1 2 3; 4 5 6; 7 8 9]
or as
A=[1 2 3
4 5 6
7 8 9]
In addition to the arithmetic operations that can be performed on a matrix, the opera-
tions in Table C.3 can be implemented.
TABLE C.3
Matrix Operations
Operation Remark
A’ Finds the transpose of matrix A
det(A) Evaluates the determinant of matrix A
inv(A) Calculates the inverse of matrix A
eig(A) Determines the eigenvalues of matrix A
diag(A) Finds the diagonal elements of matrix A
expm(A) Exponential of matrix A
378 Appendix C: Introduction to MATLAB®
C=A+ B
2 6 10
C=6 10 14
10 14 18
D = A ^3- B*C
372 432 492
D = 948 1131 1314
1524 1830 2136
e = [1 2; 3 4]
1 2
e=
3 4
f = det(e)
f=- 2
g = inv ( e )
-2.0000 1.0000
g=
1.5000 -0.5000
H = eig ( g )
-2.6861
H=
0.1861
Note that not all matrices can be inverted. A matrix can be inverted if and only if
its determinant is nonzero. Special matrices, variables, and constants are listed in
Table C.4. For example, type
≫ eye(3)
1 0 0
ans = 0 1 0
0 0 1
TABLE C.4
Special Matrices, Variables, and Constants
Matrix/Variable/Constant Remark
eye Identity matrix
ones An array of ones
zeros An array of zeros
i or j Imaginary unit or sqrt(−1)
pi 3.142
NaN Not a number
inf Infinity
eps A very small number, 2.2e−16
rand Random element
will graph data (x1,y1) in red, data (x2,y2) in blue, and data (x3,y3) in dashed line all
on the same plot.
MATLAB also allows for logarithm scaling. Rather that the plot command, we use
10
–2
–4
–6
–8
–10
0 2 4 6 8 10 12 14 16
TABLE C.5
Various Color and Line Types
y Yellow . Point
m Magenta o Circle
c Cyan x x-mark
r Red + Plus
g Green - Solid
b Blue * Star
w White : Dotted
k Black -. Dashdot
-- Dashed
Three-dimensional plots are drawn using the functions mesh and meshdom (mesh
domain). For example, to draw the graph of z = x* exp(−x^2−y^2) over the domain
−1 < x, y < 1, we type the following commands:
≫ xx = −1:.1:1;
≫ yy = xx;
≫ [x,y] = meshgrid(xx,yy);
≫ z=x.*exp(-x.^2 -y.^2);
≫ mesh(z);
0.5
–0.5
30
25
20 20
15
10 10
5
0 0
TABLE C.6
Other Plotting Commands
Command Comments
bar(x,y) A bar graph
contour(z) A contour plot
errorbar (x,y,l,u) A plot with error bars
hist(x) A histogram of the data
plot3(x,y,z) A three-dimensional version of plot()
polar(r, angle) A polar coordinate plot
stairs(x,y) A stairstep plot
stem(n,x) Plots the data sequence as stems
subplot(m,n,p) Multiple (m-by-n) plots per window
surf(x,y,x,c) A plot of 3D colored surface.
Other plotting commands in MATLAB are listed in Table C.6. The help com-
mand can be used to find out how each of these is used.
or simple text editor. Type the program and save the program in a file with an
extension.m, say filename.m; it is for this reason it is called an M-file. Once
the program is saved as an M-file, exit the Debugger window. You are now back in
Command window. Type the file without the extension.m to get results. For example,
the plot that was made above can be improved by adding title and labels and typed
as an M-files called example1.m.
≫ example1
in the Command window and hit <Enter> to obtain the result shown in Figure C.3.
To allow flow control in a program, certain relational and logical operators are
necessary. They are shown in Table C.7. Perhaps, the most commonly used flow
A sine function
10
2
10*sin(2*pi*x)
–2
–4
–6
–8
–10
0 2 4 6 8 10 12 14 16
x (in radians)
TABLE C.7
Relational and Logical Operators
Operator Remark
< Less than
≤ Less than or equal
> Greater than
≥ Greater than or equal
== Equal
~= Not equal
& And
| Or
~ Not
control statements are for and if. The for statement is used to create a loop or a
repetitive procedure and has the general form:
for x = array
[commands]
end
The if statement is used when certain conditions need to be met before an expres-
sion is executed. It has the general form:
if expression
[commands if expression is True]
else
[commands if expression is False]
end
For example, suppose we have an array y(x) and we want to determine the minimum
value of y and its corresponding index x. This can be done by creating an M-file as
shown as follows.
% example2.m
% This program finds the minimum y value and its corresponding
x index
x = [1 2 3 4 5 6 7 8 9 10]; %the nth term in y
y = [3 9 15 8 1 0 -2 4 12 5];
min1 = y(1);
for k=1:10
min2=y(k);
if(min2 < min1)
min1 = min2;
xo = x(k);
else
min1 = min1;
end
384 Appendix C: Introduction to MATLAB®
end
diary
min1, xo
diary off
Note the use of for and if statements. When this program is saved as example2.m,
we execute it in the Command window and obtain the minimum value of y as −2 and
the corresponding value of x as 7, as expected.
≫ example2
min1 =
−2
xo =
7
If we are not interested in the corresponding index, we could do the same thing using
the command
≫ min(y)
an1 x1 + an 2 x2 + + ann xn = bn
Appendix C: Introduction to MATLAB® 385
or in matrix form
AX = B
where
A is a square matrix and is known as the coefficient matrix, while X and B are vec-
tors. X is the solution vector we are seeking to get. There are two ways to solve for X
in MATLAB. First, we can use the backslash operator (\) so that
X = A\B
Second, we can solve for X as
X = A-1 B
X = inv( A) * B
We can also solve equations using the command solve. For example, given the qua-
dratic equation x2 + 2x−3 = 0, we obtain the solution using the following MATLAB
command:
indicating that the solutions are x=−3 and x=1. Of course, we can use the command
solve for a case involving two or more variables. We will see that in the following
example.
Example C.1
25x1 - 5x2 - 20 x3 = 50
-5x1 + 10 x2 - 4x3 = 0
-5x1 - 4x2 + 9x3 = 0
386 Appendix C: Introduction to MATLAB®
Solution
We can use MATLAB to solve this in two ways:
Method 1:
The given set of simultaneous equations could be written as
B = [50 0 0]¢
50
B=0
0
X = inv ( A ) * B
29.6000
X = 26.0000
28.0000
X = A\B
29.6000
X = 26.0000
28.0000
Method 2:
Since the equations are not many in this case, we can use the command solve to
obtain the solution of the simultaneous equations as follows:
3x1 - x2 - 2x3 = 1
- x1 + 6x2 - 3x3 = 0
-2x1 - 3x2 + 6x3 = 6
Answer: x1 = 3 = x3, x2 = 2.
• Use the minimum commands possible and avoid execution of extra com-
mands. This is particularly true of loops.
• Use matrix operations directly as much as possible and avoid for, do, and/
or while loops if possible.
• Make effective use of functions for executing a series of commands over
several times in a program.
• When unsure about a command, take advantage of the help capabilities of
the software.
• It takes much less time running a program using files on the hard disk than
on a floppy disk.
• Start each file with comments to help you remember what it is all about
later.
• When writing a long program, save frequently. If possible, avoid a long
program; break it down into smaller subroutines.
388 Appendix C: Introduction to MATLAB®
TABLE C.8
Other Useful MATLAB® Commands
Command Explanation
angle Phase angle
bode Plot bode plot
conj Complex conjugate
diary Save screen display output in text format
grid Provides grid lines for 2D and 3D plots
mean Mean value of a vector
min(max) Minimum (maximum) of a vector
grid Add a grid mark to the graphic window
poly Converts a collection of roots into a polynomial
polyfit Polynomial curve fitting
roots Finds the roots of a polynomial
sort Sort the elements of a vector
sound Play vector as sound
std Standard deviation of a data collection
step Unit step response
sum Sum of elements of a vector
title Plot title