Matlab User Manual: Department of Computer Science
Matlab User Manual: Department of Computer Science
Volume
UNIVERSITY OF VICTORIA
Department of Computer Science
MATLAB
User Manual
DEPARTMENT OF COMPUTER SCIENCE
Lanjing Li
Department of Computer Science
University of Victoria
PO Box 3055, STN CSC
Victoria, BC
Canada V8W 3P6
Table of Contents
Output 23
CHAPTE R 2 Format 23
Operators 7 Functions 33
Factorizations 38
Eigenvalues 40
Sparse Matrices 42
Iterative Methods 44
Polynomials 46
Polynomial Interpolation 48
Quadrature 54
Integrating Functions of
One Variable 54
Algebraic Equations 64
References 67
1
Chapter
M A T L A B U S E R M A N U A L
Accessing MATLAB
• When MATLAB opens, there are 3 windows: two on the left (Current
Directory and Command History) and one larger one on the right
(Command Window). Click inside the top left window (the Current
Directory) so that it is selected. You must change the current directory
to be C:\students instead of the one it defaults to when MATLAB starts
up. Thus, when you save M-files to the C:\students directory, MATLAB
can find them. To do this, click repeatedly on the yellow file folder icon
with the up arrow (the leftmost icon) until it “grays out”. Then scroll
down and double click the “students” folder. This will change the default
directory to C:\students.
1
M A T L A B U S E R M A N U A L
Quitting MATLAB
S
elect Exit MATLAB from File on the menu bar to exit MATLAB.
Alternatively, type exit or quit in the Command Window to quit MATLAB.
2
2
Chapter
M A T L A B U S E R M A N U A L
Basics of MATLAB
T
he Command Window, Graphics Window and Edit Window are the three
basic windows available in MATLAB .
MATLAB Windows
• Command Window: This is the primary and default window in which a
user interacts with MATLAB. Similar to any other command shells, the
prompt >> is displayed and a blinking cursor appears to the right of the
prompt. A user can type an individual command on the command line or
run a program in this window. For example, to create a vector e with two
elements, type
>> e = [ 1 0 ]
e=
1 0
3
M A T L A B U S E R M A N U A L
• Launch Pad: Launch Pad provides easy access to all of the MATLAB
products installed in your system. To view a list of all the products,
select Launch Pad from the View menu on the desktop. To run a
product, double click on the selected product listed in the Launch Pad
Window.
C O M M A N D D E S C R I P T I O N
4
M A T L A B U S E R M A N U A L
A
matrix is the fundamental data structure in MATLAB; scalars and vectors are
special cases of a matrix. The entries of a matrix can be either real numbers or
complex numbers.
Scalars
• Definition:A scalar is a number that can be either a real or complex
number. A scalar is a special case of a 1 × 1 matrix. For example:
>> x = 0.75
x=
0.7500
>> y = 3 + 4i
y=
3.0000 + 4.0000i
Vectors
• A vector is a special case of a matrix with one row or one
Definition:
column. For example:
>> u = [ 1 2 ]
u=
1 2
>> v = [ 1, -1.1, 0 ]
v=
1.0000 − 1.1000 0
>> w = [ 2; 3.6; - 1 ]
v=
2.0000
3.6000
− 1.0000
Matrices
• Definition: An m × n matrix is a two dimensional array of scalars,
consisting m rows and n columns. A space or a comma separates
consecutive entries in a row, and a semicolon or a carriage return separates
consecutive rows. For example:
5
M A T L A B U S E R M A N U A L
>> A = [ 1 2; 3 4 ]
A=
1 2
3 4
>> B = [ i, -1, 1 + i
2, -2 - i, 3 ]
B=
0 + 1.0000i - 1.0000 1.0000 + 1.0000i
2.0000 - 2.0000 - 1.0000i 3.0000
>> v = 1 : 4
v=
1 2 3 4
>> w = 12 : -3 : 0
w=
12 9 6 3 0
>> y = 5 : -2 : 0
y=
5 3 1
>> x = 0 : 2 : 5
x=
0 2 4
6
M A T L A B U S E R M A N U A L
A from the selected rows and columns. If the row and column indices are
consecutive, then A(r : s, p : q) denotes the submatrix from rows r, …, s
and from columns p, …, q. A colon ( : ) can be used to select all of the
row or column indices. For example:
>> A = [ 1 2 3; 4 5 6; 7 8 9 ]
A=
1 2 3
4 5 6
7 8 9
>> A ( 3, 3 )
ans =
9
>> B = A ( [ 1 3 ], [ 2 3 ] )
B=
2 3
8 9
>> C = A ( 1 : 2, 2 : 3 )
C=
2 3
5 6
>> D = A ( :, 1 : 2 )
D=
1 2
4 5
7 8
Operators
• Arithmetic Operators: The table below lists all of the MATLAB
arithmetic operators. Other operators, such as logical and relational
operators, are described in the section Flow of Control.
7
M A T L A B U S E R M A N U A L
O P E R A T O R D E S C R I P T I O N
+ Addition
- Subtraction
* Matrix multiplication
.* Entry-wise multiplication
/ Matrix left division
./ Left entry-wise Division
\ Matrix right division
.\ Right entry-wise division
^ Matrix exponentiation
.^ Entry-wise exponentiation
' Matrix transpose
.' Nonconjugated transpose
• Examples:
⎡ 1⎤ ⎡1⎤
Suppose that x = 0.75, v = ⎢⎢− 1.1⎥⎥ , w = ⎢0⎥ , u = ⎡ 1⎤ , A = ⎡1 2⎤
⎢ ⎥ ⎢3⎥ ⎢3 4⎥
⎢⎣ 0⎥⎦ ⎢⎣0⎥⎦ ⎣ ⎦ ⎣ ⎦
⎡1 3 ⎤
and B = ⎢ ⎥.
⎣7 2 ⎦
>> 2 * x / 5
ans =
0.3000
>> v – w
ans =
0
− 1.1000
0
>> x + 10 * v
ans =
10.7500
− 10.2500
0.7500
8
M A T L A B U S E R M A N U A L
>> 2 + A/2
ans =
2.5000 3.0000
3.5000 4.0000
>> A \ u
ans =
1
0
>> A * u
ans =
7
15
>> u * u'
ans =
1 3
3 9
>> u .* u
ans =
1
9
>> u' * u
ans =
10
>> A./B
ans =
1.0000 0.6667
0.4286 2.0000
>> A/B
ans =
0.6316 0.0526
1.1579 0.2632
9
M A T L A B U S E R M A N U A L
>> A * B
ans =
15 7
31 17
>> A( 1, 2 )^2 * B( 2, 2 )
ans =
8
L E V E L O P E R A T O R
1 Parentheses ( )
2 Transpose (.'), power (.^), complex conjugate transpose ( ' ), matrix power(^)
3 Unary plus (+), unary minus (-), logical negation (~)
4 Multiplication (.*), right division (./), left division (.\), matrix multiplication (*),
matrix right division (/), matrix left division (\)
5 Addition (+), subtraction (-)
6 Colon operator (:)
7 Less than (<), less than or equal to (<=), greater than (>),
greater than or equal to (>=), equal to (==), not equal to (~=)
8 Logical AND (&)
9 Logical OR (|)
Character Strings
• Definition: A character string, which is enclosed by a pair of single quotes,
is an array of characters. The internal representation of each character is a
numerical value, and requires 2 bytes for storage. For example,
10
M A T L A B U S E R M A N U A L
C O M M A N D D E S C R I P T I O N
Variables
A
s in other programming languages, you can use variables to store values in the
current session or in an M-file. There are two types of variables, local and
global.
Declaration
• Implicit Declaration: MATLAB does not require explicit declarations for
its variables (with the exception of global variables used in MATLAB
functions; see 'Global Variables' below). When MATLAB encounters a
new variable name, it automatically creates the variable and allocates the
appropriate amount of storage.
11
M A T L A B U S E R M A N U A L
Global Variables
• Explicit Declaration: A global variable can be declared using the global
command so that more than one function can share a single copy of the
variable. You must declare the variable as global at the beginning of every
function that requires access to it. Similarly, you must declare it as global
from the command line to enable your active workspace to access it.
Using uppercase characters for a global variable name is recommended.
Flow of Control
I
n MATLAB, flow of control depends on the results of evaluating logical
expressions using relational and logical operators defined in the tables below.
These operators compare corresponding entries of matrices with the same
dimensions. The Boolean values true and false are stored and displayed as 1
and 0, respectively.
O P E R A T O R D E S C R I P T I O N
• Logical Operators:
O P E R A T O R D E S C R I P T I O N
& And
| Or
~ Not
• Examples:
12
M A T L A B U S E R M A N U A L
>> [ 2 3 5 ] > [ 0 3 4 ]
ans =
1 0 1
>> [ 1 2; 3 4 ] <= [ 1 5; 6 2 ]
ans =
1 1
1 0
Note: To test if two matrices are identical, use isequal . For example, if A
⎡1 2 ⎤ ⎡1 2⎤
= ⎢ ⎥ and C = ⎢ ⎥ , then
⎣0 1 ⎦ ⎣1 0⎦
Control Statements
• if statement: The if statement executes a group of statements if the
evaluated expression is true. The optional elseif and else provide
alternatives for execution of different groups of statements.
• Syntax:
if expression
statements
else
statements
end
if expression1
statements
elseif expression2
statements
…
else
statements
end
• Example:
13
M A T L A B U S E R M A N U A L
>>if x > 10
z = 1;
else if y > 0
z = 2;
else
z = 3;
end
• Syntax:
switch expression
case test_expression1
statements
case test_expression2
statements
…
otherwise
statements
end
• Example:
>>switch x
case 0
y = 0;
case 1
y = x + 2;
otherwise
y = 10;
end
• Syntax:
14
M A T L A B U S E R M A N U A L
• Example:
>> for n = 1 : 4
x( n ) = n/10 * pi;
end
>> x
x=
0.3142 0.6283 0.9425 1.2566
• Syntax:
while expression
statements
end
• Example:
>> p =1; u = 1;
while p < 16
p = p * 2;
u = [ u, p ];
end
>> u
u=
1 2 4 8 16
• Syntax:
while expression
statements
continue
statements
end
15
M A T L A B U S E R M A N U A L
while expression
statements
break
statements
end
• Example:
>> m = 1; n = 0;
>> while n <= 1000
m = m/3;
if ( 1 + m ) > 1
n = n + 1;
continue
end
m = m*3
break
end
m=
1.7989e-016
M-File Basics
B
esides using the interactive computational environment, you can also write
programs in the MATLAB language and store them in files. These files are
called M-files.
Creating M-Files
An M-file is just an ordinary text file and hence it can be created using any text
editor. As mentioned earlier, MATLAB provides a default M-file editor for all
platforms. To open the default editor, select New and then M-File from the File
menu, or type edit in the Command Window. To save an M-file, from the File
menu select Save for an existing file or Save as for a new file. An M-file name
16
M A T L A B U S E R M A N U A L
must have a '.m' extension after the file name. There are two types of M-files,
script files and function files.
M-file: myScriptFile.m
A = [1 2 3; 4 5 6; 7 8 0]
p = poly (A)
r = roots (p)
• Function Files: Similar to a script file, a function file is a file that contains
one or more functions. The first function in the file is the primary function
and the rest are subfunctions. A subfunction can only be called by the
primary function and other subfunctions within the same file. The primary
function or a subfunction can contain any valid MATLAB statements.
The output variables and the input variables are both optional. Note that
MATLAB function names are specified in the same way as variable names
(that is, they begin with a letter and are up to 31 characters long).
To save a function file, one must use the primary function name for the
M-file. For example, if the primary function name is EigValues, the file
name is EigValues.m
M-file: EigValues.m
17
M A T L A B U S E R M A N U A L
>> C = [ 1 2 3; 4 5 6; 7 8 0 ]
C=
1 2 3
4 5 6
7 8 0
coef =
1.0000 -6.0000 -72.0000 -27.0000
M-file: EigValues.m
18
M A T L A B U S E R M A N U A L
if ( nargout == 2 )
coeffs = p;
end
M-file: BigTrace.m
t = sum(diag(C));
19
M A T L A B U S E R M A N U A L
Running M-Files
• From the Command Line: To invoke an M-file (either a function file or a
script file), type the name of the file without the '.m' extension from the
command line in the Command Window. For example, you can call the
function BigTrace from the command line as follows.
Suppose A = [1 2 3; 4 5 6; 7 8 0] and B = [3 4; 5 6] .
>> BigTrace( A, B )
ans =
9
C O M M A N D D E S C R I P T I O N
20
M A T L A B U S E R M A N U A L
M
ATLAB allows user input during runtime, saves a copy of a MATLAB
session in a file, and saves data files in a variety of formats. In addition,
there are commands to control how data are displayed.
Input
• User Input: User input can be prompted and obtained interactively during
runtime. The syntax for the command input is given below. The value
entered by a user can be any valid MATLAB expression or a character
string if the second argument 's' is used.
inValues = input(prompt_string)
inValues = input(prompt_string,'s')
• Example:
>> isQuit = input( ' Do you want to exit the current session? Y/N [Y]: ',
's' );
>> if ( isQuit == 'Y' | isempty( isQuit ) )
save;
quit;
else
quit cancel;
end
Output
• Save and Load Variables: Before you exit or quit the current workspace,
you can use the save command to save all the variables and their current
values. In a new session, you can use the load command to restore them.
For example:
Note that if save and load are used without a specified file name, MATLAB
uses a default file name, matlab.mat.
• Output to the Screen: Several output functions are available. Here are a
few examples.
21
M A T L A B U S E R M A N U A L
When you type a variable name, MATLAB displays the variable name and its
value by default. Sometimes it is desirable to display only the value. For
example, suppose B = [3 4; 5 6] . Then to display the value of the
matrix B with column labels, type
Note that the number 7 in the format string is the field width, the number 2 is
the number of decimal digits after the decimal point, and the escape character
\n is a new line terminator.
>> u = [ 1 2 ];
>> v = u + 3;
• Keep a Session Log: The diary command can be used to save the entire
working session. This command spools all the activities or events in the
Command Window to a text file. For example, to save the current session,
type
If diary is used without a specified file name, then MATLAB uses a default file
name diary.
22
M A T L A B U S E R M A N U A L
Format
For online help
MATLAB stores numbers to a relative precision of
type help format or
approximately 16 decimal digits. By default MATLAB displays
select MATLAB Help numbers in the short format (4 decimal places). To print a value
from Help menu. in any of the formats given below, enter format type on the
command line. For example:
The following table illustrates the additional format types supported by MATLAB.
F O R M A T E X A M P L E S
23
M A T L A B U S E R M A N U A L
Graphics
M
ATLAB has extensive tools for displaying various data as graphs. It also
provides facilities for annotating and printing graphs. In the following
section, some examples are presented to illustrate how a graph can be
created using these tools. To invoke the graphics editor, type figure in the
Command Window.
Basic Plots
The most basic graph is a simple 2-D plot. One form of the syntax for the plot
command is plot (x_values,y_values,'style-option'). x_values is a
For online help
type help graph2d
vector that contains the points on the x-coordinate, while
y_values contains the points on the y-coordinate. style-option is a
or select MATLAB
Help from Help parameter that defines the line style, the marker, and the color
menu. used in a graph. If this parameter is not entered, MATLAB uses
the default style. Style options are summarized in the following
table.
24
M A T L A B U S E R M A N U A L
C O L O R L I N E S T Y L E M A R K E R
25
M A T L A B U S E R M A N U A L
Graph of a Function
MATLAB provides commands ezplot and fplot for plotting mathematical functions.
The syntaxes for the commands are ezplot ('function', [xmin, xmax, ymin, ymax]) and fplot
('function', [xmin, xmax, ymin, ymax]), respectively. Both commands plot a function in a
specified range. However, if a line style different from the default is required, then fplot
( 'function', [xmin, xmax, ymin, ymax], 'style-option') should be used. For example, let us
first create a function in an M-file called myFunction.m and then use the command
ezplot ('myFunction',[ 0 2*pi 0 12 ]) to generate the graph on the specified range. The
output is shown in Figure 2.2a. To generate the same plot using a dotted line instead
of a solid line (default), use fplot ('myFunction',[ 0 2*pi 0 12 ], ' :xr '). Note that ':xr' means
a dotted red line with cross markers is used in the plot. The output is shown in Figure
2.2b.
M-file: myFunction.m
function y = myFunction(x)
26
M A T L A B U S E R M A N U A L
>> plot( x, y )
>> title( 'X-Y Plot' )
>> ylabel( 'cos(2*t)' )
>> xlabel( 'sin(3*t)' )
>> text( -0.2, 0.4, 'A symmetry graph' )
27
M A T L A B U S E R M A N U A L
select MATLAB
similarly, ymin and ymax define the smallest and largest end
Help from Help points for y-axis. For example, we can change the ranges for the
menu. axes in Figure 2.2a to [ 0, 4 ] and [ 0, 8 ] as follows. The output
is shown in Figure 2.4.
28
M A T L A B U S E R M A N U A L
For online help • Using the Command subplot: The MATLAB function
type help subplot subplot can be used to plot data into different sub-
or select MATLAB regions within the same graphics window. The
Help from Help command subplot(m,n,i) divides the graphics window
menu. into an m by n matrix of small sub-regions and
generates the next figure in the ith sub-region. The sub-
regions are numbered row-wise.
For example, the following statements plot a set of data in four different sub-
regions of the graphics window in Figure 2.5. The command subplot(2,2,1) is set
for plot(t,z) to be generated in the first sub-region in first row. Similarly,
subplot(2,2,2) is set for plot(t,2*q) in the second sub-region in the first row, and so
on.
29
M A T L A B U S E R M A N U A L
>> subplot( 2, 2, 4 )
>> fplot( '[ sin( x ), cos( 2*x ), 1/( 1+x ) ]',[ 0 5*pi -1.5 1.5 ] )
• Using a Matrix: To create multiple plots in a single graph (as in the last
sub-region in Figure 2.5), one can also use a matrix. Each column of the
matrix contains the functional values that are to be plotted as one graph.
In the following, note that cos(x) is a row vector of functional values, and
cos(x)' is a column vector ( ' is the transpose operator). The following
example is illustrated in Figure 2.6a.
If different styles are desired for different plots, replace plot(x,Y) with, for
example, plot(x,Y(:,1),'--',x,Y(:,2),'-.',x,Y(:,3)). The result is shown in Figure 2.6b.
30
M A T L A B U S E R M A N U A L
• Using the Command hold: The third way to create multiple plots in the
same graphics window is to use the command hold. hold on freezes the
current plot in a graphics window and allows subsequent plots to be
generated in the same window. An example is shown below and the
output is displayed in Figure 2.7.
31
M A T L A B U S E R M A N U A L
>> hold on
>> plot( cos( t ) )
>> hold off
For example, the following statement will save the current graph into a file named as
mygraph.eps.
You can export a graph with a specified format using the command saveas. For
example, the command below saves the current graph in the jpg format.
32
M A T L A B U S E R M A N U A L
33
3
Chapter
M A T L A B U S E R M A N U A L
Linear Algebra
M
ATLAB has an extensive set of functions for computations in linear
algebra, such as functions for computing the inverse and the determinant of
a matrix. In the following section, several fundamental concepts from linear
algebra are defined and some examples are given to illustrate how to use
these MATLAB functions to solve linear algebra problems.
1/ p
⎛ n ⎞
⎜ p⎟
x p≡ ∑x ⎜
⎜ i ⎟
⎟
for 1 ≤ p < ∞ .
⎝ i =1 ⎠
34
M A T L A B U S E R M A N U A L
x ∞ ≡ max { x 1 ,..., x n }
For example, to compute the max norm of the vector x used in the
previous example, type
Ax p
A p ≡ max
x≠0
x p
n
A ∞ ≡ max ∑ a ij , and
1≤ i ≤ n j =1
Inverses
• Inverse of a Square Matrix: The inverse of a square matrix A is the
matrix A-1 such that A-1A = AA-1 = I,
where I is the identity matrix. The
35
M A T L A B U S E R M A N U A L
>> A = [ 1 2; 3 4 ]
A=
1 2
3 4
>> B = inv( A )
B=
- 2.0000 1.0000
1.5000 - 0.5000
>> I = B * A
I=
1.0000 0
0.0000 1.0000
>> A = [ 1 2 3; 5 7 9 ]
A=
1 2 3
5 7 9
>> B = pinv( A )
B=
- 1.3889 0.4444
- 0.2222 0.1111
0.9444 - 0.2222
>> B * A
ans =
0.8333 0.3333 - 0.1667
0.3333 0.3333 0.3333
- 0.1667 0.3333 0.8333
36
M A T L A B U S E R M A N U A L
>> A * B
ans =
1.0000 0.0000
- 0.0000 1.0000
>> A * B * A
ans =
1.0000 2.0000 3.0000
5.0000 7.0000 9.0000
>> B * A * B
ans =
- 1.3889 0.4444
- 0.2222 0.1111
0.9444 - 0.2222
Transposes
The transpose of a matrix A is obtained by interchanging the rows and columns of
A, and is computed by A' in MATLAB.
>> A = [ 1 2; 3 4 ]
A=
1 2
3 4
>> A'
ans =
1 3
2 4
37
M A T L A B U S E R M A N U A L
>> A'
ans =
1.0000 - 1.0000i - 3.0000
2.0000 + 1.0000i 0 + 2.0000i
Determinants
• Determinant of a Square Matrix: The determinant of a square matrix A is
calculated using the triangular factors obtained from Gaussian elimination
and can be computed by det(A). Suppose A = [1 2; 3 4] .
>> det( A )
ans =
-2
Rank
• Rank of a Matrix: The rank of a matrix A is the largest number of
columns (or rows) of A that constitutes a linearly independent set. To
compute the rank of a matrix, use the function rank(A) in MATLAB. For
example, for the matrix A = [1 2; 3 4] :
>> rank( A )
ans =
2
Factorizations
• LU Factorization of a Matrix: For every square matrix A, there exist a
lower triangular matrix L, an upper triangular matrix U, and a permutation
matrix P such that PA = LU. To compute the LU factors for a matrix by
Gaussian elimination with partial pivoting, use the function lu(A) in
MATLAB. For example, suppose A = [1 3; 2 4] .
U=
2 4
0 1
38
M A T L A B U S E R M A N U A L
P=
0 1
1 0
>> A = [ 1 1 1; 1 2 3; 1 3 6 ]
A=
1 1 1
1 2 3
1 3 6
>> R = chol( A )
R=
1 1 1
0 1 2
0 0 1
>> R' * R
ans =
1 1 1
1 2 3
1 3 6
Suppose A = [1 0 1; 2 2 3; 0 1 3].
39
M A T L A B U S E R M A N U A L
R=
- 2.2361 - 1.7889 - 3.1305
0 - 1.3416 - 2.5342
0 0 1.6667
Eigenvalues
• Eigenvalues and Eigenvectors of a Matrix: If A is a square matrix and if
a scalar λ and a nonzero vector x satisfy the equation Ax = λx, then λ is
called an eigenvalue and x is called an eigenvector of the matrix A. The
function eig(A) allows you to compute eigenvalues and eigenvectors of a
matrix. Suppose A = [5 − 3 2; − 3 8 4; 1 3 − 9] .
D=
10.1218 0 0
0 3.8243 0
0 0 - 9.9461
>> A * V( :, 1 )
ans =
- 4.7472
8.8666
1.1429
40
M A T L A B U S E R M A N U A L
>>D( 1, 1 ) * V( :, 1 )
ans =
- 4.7472
8.8666
1.1429
D=
3 0 0
0 2 0
V=
0.7454 - 0.0000 - 0.6667
0.2981 0.8944 0.3333
0.5963 - 0.4472 0.6667
>> U * D * V'
ans =
1.0000 2.0000 - 0.0000
2.0000 - 0.0000 2.0000
41
M A T L A B U S E R M A N U A L
Sparse Matrices
A sparse matrix is a matrix that contains a relatively large number of zero entries.
MATLAB provides a set of functions that stores only the nonzero entries of a sparse
matrix and eliminates arithmetic operations on the zero entries.
• Storage Information: To find out the information about sparse and full
versions of the same matrix, use the command whos. Suppose A =
⎡1 0 0 0⎤
⎢0 0 0 2⎥⎥
⎢ and B = sparse (A).
⎢0 1 5 0⎥
⎢ ⎥
⎣0 0 3 0⎦
>> whos
Name Size Bytes Class
• Create a Sparse Matrix: For a sparse matrix, MATLAB uses three arrays
to store only the nonzero entries, their row indices, and their column
indices. To create a sparse matrix, use the command sparse( i, j, s, m, n ),
where i and j are the vectors that contain row and column indices for the
nonzero entries of the matrix; s is a vector that contains a list of nonzero
values whose indices are defined by the corresponding i, j pairs; m is the
row dimension of the sparse matrix; and similarly n is the column
dimension. To create a sparse matrix B of the above matrix A, for
example, enter the following.
>> i = [ 1 2 3 3 4 ];
>> j = [ 1 4 2 3 3 ];
>> s =[ 1 2 1 5 3 ];
>> B = sparse( i, j, s, 4, 4 )
B=
(1,1) 1
(3,2) 1
(3,3) 5
(4,3) 3
(2,4) 2
Note that the resulting matrix above is the same as the one obtained using
sparse(A).
42
M A T L A B U S E R M A N U A L
>> nnz( B )
ans =
5
>> nonzeros( B )
ans =
1
1
5
3
2
>> spy( B )
43
M A T L A B U S E R M A N U A L
C O M M A N D D E S C R I P T I O N
Iterative Methods
Two classes of methods can be used to solve systems of simultaneous linear equations,
direct methods and iterative methods. Direct methods are more efficient for small
linear systems; however, they may be very costly in terms of storage and computational
time for large sparse linear systems. If convergent, iterative methods compute an
approximate solution to a linear system and this may be much more efficient than
using a direct method. In this section, we describe how to solve a linear system using
MATLAB functions based on iterative methods.
44
M A T L A B U S E R M A N U A L
C O M M A N D D E S C R I P T I O N
Perform the incomplete Cholesky factorization and use the factor R' of the
matrix A as the preconditioner M. Note that M-1Ax = ( R' )-1Ax = ( R' )-1b, and
( R' )-1A is better conditioned than A.
45
M A T L A B U S E R M A N U A L
>> y = A * x;
M
ATLAB provides a number of functions for manipulating polynomials,
such as for root finding and curve fitting. In the following section, some
examples are given to illustrate their use.
Polynomials
• Representation of a Polynomial: MATLAB stores the coefficients of a
polynomial in a row vector, ordered by descending powers. For example,
the coefficients of the polynomial p( x) = x 2 − 1 can be entered in
MATLAB as follows.
>> p = [ 1 0 -1 ]
p=
1 0 -1
>> r = roots( p )
r=
−1
1
46
M A T L A B U S E R M A N U A L
>> p = poly ( A )
p=
1.0000 - 6.0000 - 72.0000 - 27.0000
>> roots( p )
ans =
12.1229
- 5.7345
- 0.3884
>> p = [ 1 0 -1 ];
>> polyval( p, 2 )
ans =
3
>> x =1 : 0.2 : 2
x=
1.0000 1.2000 1.4000 1.6000 1.8000 2.0000
>> p = polyfit( x, y, 3 )
p=
- 0.9144 4.9494 - 9.4616 7.4432
47
M A T L A B U S E R M A N U A L
• Other Useful Functions: The table below lists some useful polynomial
functions.
C O M M A N D D E S C R I P T I O N
Polynomial Interpolation
• One Dimensional Interpolation: A polynomial p( x) in one variable x
interpolates a given set of values ( x i , y i ) , 1 ≤ i ≤ n, if p ( x i ) = y i for i
= 1, 2,…, n.
48
M A T L A B U S E R M A N U A L
M E T H O D D E S C R I P T I O N
49
M A T L A B U S E R M A N U A L
M E T H O D D E S C R I P T I O N
>> x = -4 : 0.5 : 4;
>> y = 0 : 0.5 : 8;
>> [X, Y] = meshgrid( x, y );
>> Z = peaks( X, Y );
>> xx = linspace( -4, 4, 50 );
>> yy = linspace( 0, 8, 50 );
>> [XX, YY] = meshgrid( xx, yy );
>> ZZ = interp2( X, Y, Z, XX, YX, 'bicubic' );
50
M A T L A B U S E R M A N U A L
51
M A T L A B U S E R M A N U A L
The resulting plot is shown below. This is the same example as the one in
the one-dimensional interpolation, except that the spline function is used
instead.
If there is more than one set of interpolated values, the pp-form of the
spline function can be used in combination with the function ppval(pp, xx).
For example:
52
M A T L A B U S E R M A N U A L
'MarkerFaceColor', 'r' )
>> axis( [ 0 3.5 -1 1 ] )
>> hold off
coefs =
0.1159 - 0.6123 0.0365 1.0000
0.1159 - 0.3392 - 0.7108 0.7071
0.1858 - 0.2026 - 0.9236 0.3827
0.1356 0.0163 - 0.9968 0.0000
0.1356 0.3357 - 0.7203 - 0.7071
Note that the values of the breaks are the entries of the vector x above,
and each row of the matrix coefs contains the coefficients of one of the
cubic polynomials of the spline function.
53
M A T L A B U S E R M A N U A L
Quadrature
M
ATLAB provides a set of functions for evaluating definite integrals. In the
following section, examples are given to illustrate the basic usage of these
functions.
q = quad( fun, a, b )
dx
∫
b
F ( x) =
a 2x 2 + 3
M-file: myIntegral.m
function y = myIntegral(x)
y = 1 ./ ( 2 .* x.^2 + 3 );
>> n = 15;
>> for m = 1 : n
b = m * 0.1;
Int(m) = quad( @myIntegral, 0, b );
end
54
M A T L A B U S E R M A N U A L
dx
∫
2
Suppose F ( x) = . An approximation of this integral using trapz
1 x
55
M A T L A B U S E R M A N U A L
S O L V E R S D E S C R I P T I O N M E T H O D
M
ATLAB provides software for solving both initial value and boundary value
problems. In the following section, examples are given to illustrate how to
solve initial value problems (a single differential equation and a system of
differential equations).
First create the function myODE below and save the function in the file
myODE.m.
M-file: myODE.m
function dy = myODE(t,y)
56
M A T L A B U S E R M A N U A L
dy = y - t * t + 1;
>> tspan = [ 0 2 ];
>> yzero = 0.5;
>> [t, y] = ode45( @myODE, tspan, yzero );
>> w = [ 0 : .1 : 2 ];
>> f = ( w + 1 ) .^ 2 - 0.5 .* exp( w );
>> % Plot the exact solution
>> plot( w, f, '-' )
>> hold on
>> % Plot the computed solution
>> plot( t, y, 'o', 'MarkerEdgeColor', 'r', 'MarkerFaceColor', 'r' )
57
M A T L A B U S E R M A N U A L
M-file: myODE2.m
function dy = myODE2(t,y)
>> tspan = [ 0 1 ];
>> yzero =[ -0.4; -0.6 ];
>> [t, y] = ode45( @myODE2, tspan, yzero );
>> w = [ 0 : 0.05 :1 ];
>> f = 0.2 .* exp( 2 .* w ) .* ( sin( w ) - 2 .* cos( w ) );
>> % Plot the exact solution
>> plot( w, f, '-' )
>> hold on
>> % Plot the computed solution
>> plot( t, y(:, 1), 'o', 'MarkerEdgeColor', 'r', 'MarkerFaceColor', 'r' )
58
M A T L A B U S E R M A N U A L
To plot the actual values and the computed values of y ' , type
>> w = [ 0 : 0.05 :1 ];
>> f = 0.2 .* exp( 2 .* w ) .* ( 4 .* sin( w ) - 3 .* cos( w ) );
>> % Plot the exact solution
>> plot( w, f, '-' )
>> hold on
>> % Plot the computed solution
>> plot( t, y(:, 2), 'o', 'MarkerEdgeColor', 'r', 'MarkerFaceColor', 'r' )
59
M A T L A B U S E R M A N U A L
• ODE Function Summary: The table below lists the MATLAB initial value
problem solvers.
S O L V E R S D E S C R I P T I O N M E T H O D
V
ersion 6 of MATLAB provides a solver for solving certain classes of
parabolic and elliptic partial differential equations. In the following section,
examples are given to illustrate how to use the solver.
⎛ ∂u ⎞ ∂u ∂ ⎛ ⎛ ∂u ⎞ ⎞ ⎛ ∂u ⎞
c⎜ x, t , u, ⎟ = x − m ⎜⎜ x m f ⎜ x, t , u , ⎟ ⎟⎟ + s⎜ x, t , u, ⎟ ,
⎝ ∂x ⎠ ∂t ∂x ⎝ ⎝ ∂x ⎠ ⎠ ⎝ ∂x ⎠
where t 0 ≤ t ≤ t f , a ≤ x ≤ b , and m = 0, 1 or 2.
⎛ ∂u ⎞
p ( x, t , u ) + q ( x, t ) f ⎜ x , t , u , ⎟ = 0 .
⎝ ∂x ⎠
60
M A T L A B U S E R M A N U A L
MATLAB provides a PDE solver pdepe. The basic syntax of this solver
is:
∂u ∂ 2u
( x, t ) − 2 ( x , t ) = 0 , 0 < x < 1, t > 0,
∂t ∂x
u ( x,0) = sin(πx), 0 ≤ x ≤ 1.
∂u ∂ ⎛ ∂u ⎞
= x0 ⎜ x0 ⎟+0
∂t ∂x ⎝ ∂x ⎠
⎛ ∂u ⎞
c⎜ x, t , u , ⎟ = 1
⎝ ∂x ⎠
⎛ ∂u ⎞ ∂u
f ⎜ x, t , u , ⎟ =
⎝ ∂x ⎠ ∂x
⎛ ∂u ⎞
s ⎜ x, t , u , ⎟ = 0
⎝ ∂x ⎠
61
M A T L A B U S E R M A N U A L
M-file: pdeHeat.m
c = 1;
f = DuDx;
s = 0;
M-file: pdeHeatic.m
u0 = sin(pi*x);
∂u
u (0, t ) + 0 ⋅ (0, t ) = 0 at x = 0
∂x
∂u
u (1, t ) + 0 ⋅ (1, t ) = 0 at x = 1
∂x
M-file: pdeHeatbc.m
pl = ul;
ql = 0;
62
M A T L A B U S E R M A N U A L
pr = ur;
qr = 0;
>> m = 0;
>> x = linspace( 0, 1, 20 );
>> t = linspace( 0, 2, 5 );
>> sol = pdepe( m, @pdeHeat, @pdeHeatic, @pdeHeatbc,x,t );
>> u = sol( :, :, 1 );
>> surf( x, t, u )
>> title( 'Numerical solution to Heat Equation' )
>> xlabel( 'Distance x' )
>> ylabel( 'Time t' )
63
M A T L A B U S E R M A N U A L
T
here are a few other useful algebraic functions and functions for numerical
analysis, which are described as follows.
64
M A T L A B U S E R M A N U A L
• Maximum and Minimum Entries of an Array: The functions max and min
return the largest and the smallest entries, respectively, along a specified
dimension of an array. For example:
>> max ( w )
ans =
4.1000
• Sum and Cumulative Sum: The function sum computes the sum of the
entries of an array along a specified dimension. Similarly, the function
cumsum computes the cumulative sum of the entries of an array. For
example:
>> A = [ 1 2 3; 5 7 9; 0 4 1 ]
A=
1 2 3
5 7 9
0 4 1
>> sum( A )
ans =
6 13 13
>> cumsum( A )
ans =
1 2 3
6 9 12
6 13 13
65
M A T L A B U S E R M A N U A L
>> A = [ 1 2 3; 5 7 9; 0 4 1 ]
A=
1 2 3
5 7 9
0 4 1
>> prod( A )
ans =
0 56 27
>> cumprod( A )
ans =
1 2 3
5 14 27
0 56 27
• Sort Elements: The function sort sorts elements in ascending order. For
example:
>> w = [ -1 6 -4 0 ];
>> sort( w )
ans =
− 4 −1 0 6
>> C = [ 2 5 8; 1 6 10; 3 6 5 ]
C=
2 5 8
1 6 10
3 6 5
>> diff( C )
ans =
−1 1 2
2 0 −5
66
A
M A T L A B U S E R M A N U A L
References
[1] Desmond J. Higham and Nicholas J. Higham. MATLAB Guide. Society for
Industrial and Applied Mathematics, Philadelphia, PA, USA, 2000. ISBN 0-89871-469-
9.
[2] Getting Started with MATLAB Version 6. The Math Works, Inc., Natick, MA, USA,
2000.
[4] Rudra Pratap. Getting Started with MATLAB 5: A Quick Introduction for Scientists and
Engineers. Oxford University Press, Inc., New York, New York, USA, 1999. ISBN 0-
19-512947-4.
[5] Richard L. Burden and J. Douglas Faires. Numerical Analysis. PWS Publishing
Company, USA, 1993. ISBN 0-534-93219-3.
[6] Using MATLAB Version 6. The Math Works, Inc., Natick, MA, USA, 2000.
[7] Roger A. Horn. Matrix Analysis. Cambridge University Press, Cambridge, United
Kingdom, 1985. ISBN 0-521-38632-2.
[8] David S. Watkins. Fundamentals of Matrix Computations. Jon Wiley & Sons, Inc, New
York, New York, USA, 1991. ISBN 0-471-61414-9.
67
68