Matlab
Matlab
These slides are a supplement to the book Numerical Methods with Matlab: Implementations and Applications, by Gerald W. Recktenwald, c 20002006, Prentice-Hall, Upper Saddle River, NJ. These slides are copyright c 20002006 Gerald W. Recktenwald. The PDF version of these slides may be downloaded or stored or printed only for noncommercial, educational use. The repackaging or sale of these slides in any form, without written consent of the author, is prohibited. The latest version of this PDF le, along with other supplemental material for the book, can be found at www.prenhall.com/recktenwald or web.cecs.pdx.edu/~gerry/nmm/.
Version 1.1
page 1
Overview
(1)
Basic Matlab Operations Starting Matlab Using Matlab as a calculator Introduction to variables and functions Matrices and Vectors: All variables are matrices. Creating matrices and vectors Subscript notation Colon notation
page 2
Overview
Additional Types of Variables Complex numbers Strings Polynomials Working with Matrices and Vectors Some basic linear algebra Vectorized operations Array operators Managing the Interactive Environment Plotting
NMM: Interactive Computing with Matlab
(2)
page 3
Starting Matlab
Double click on the Matlab icon, or on unix systems type matlab at the command line. After startup Matlab displays a command window that is used to enter commands and display text-only results. Enter Commands at the command prompt: >> EDU> for full version for educational version
Matlab responds to commands by printing text in the command window, or by opening a gure window for graphical output. Toggle between windows by clicking on them with the mouse.
NMM: Interactive Computing with Matlab page 4
Matlab Desktop
Command Prompt:
Enter typed commands here. Text results are displayed here.
Launch Pad/Workspace:
Used to browse documentation, or view values of variables in the workspace Select Launch Pad tab or Workspace tab
page 5
Matlab Desktop
The desktop provides dierent ways of interacting with Matlab Entering commands in the command window Viewing values stored in variables Editing statements in Matlab functions and scripts Creating and annotating plots
page 6
Matlab as a Calculator
Enter formulas at the command prompt
>> 2 + 6 - 4 ans = 4 >> ans/2 ans = 2 (press return after 4)
(1)
page 7
Matlab as a Calculator
Dene and use variables
>> a = 5 a = 5 >> b = 6 b = 6 >> c = b/a c = 1.2000
(2)
page 8
Built-in Variables
pi (= ) and ans are a built-in variables
>> pi ans = 3.1416 >> sin(ans/4) ans = 0.7071
page 9
Built-in Functions
Many standard mathematical functions, such as sin, cos, log, and log10, are built-in
>> log(256) ans = 5.5452 >> log10(256) ans = 2.4082 >> log2(256) ans = 8 log(x) computes the natural logarithm of x
page 10
In Matlab version 6 and later the doc function opens the on-line version of the manual. This is very helpful for more complex commands.
>> doc plot
page 11
On-line Help
Syntax:
help functionName
(1)
Example:
>> help log
produces
LOG Natural logarithm. LOG(X) is the natural logarithm of the elements of X. Complex results are produced if X is not positive. See also LOG2, LOG10, EXP, LOGM.
The help function provides a compact summary of how to use a command. Use the doc function to get more in-depth information.
NMM: Interactive Computing with Matlab page 12
On-line Help
>> doc plot
(2)
page 13
produces
ACOS ACOSH COS COSH Inverse cosine. Inverse hyperbolic cosine. Cosine. Hyperbolic cosine.
page 14
Use the command window for short sequences of calculations Later well learn how to build reusable functions for more complex tasks. The command window is good for testing ideas and running sequences of operations contained in functions Any command executed in the command window can also be used in a function. Lets continue with a tour of interactive computing.
page 15
(1)
Results of intermediate steps can be suppressed with semicolons. Example: Assign values to x, y, and z, but only display the value of z in the command window:
>> x = 5; >> y = sqrt(59); >> z = log(y) + x^0.25 z = 3.5341
page 16
(2)
Type variable name and omit the semicolon to print the value of a variable (that is already dened)
>> x = 5; >> y = sqrt(59); >> z = log(y) + x^0.25 z = 3.5341 >> y y = 7.6811
( = log(sqrt(59)) + 5^0.25 )
page 17
Use commas or semicolons to enter more than one statement at once. Commas allow multiple statements per line without suppressing output.
>> a = 5; b = sin(a), b = -0.9589 c = 74.2099 c = cosh(a)
page 18
Note: mySum and mysum are dierent variables. Matlab is case sensitive.
page 19
(1)
value of an expression when that expression is not assigned to a variable oating point precision
(3.141492 . . .)
largest positive oating point number smallest positive oating point number
page 20
(2)
Rule: Only use built-in variables on the right hand side of an expression. Reassigning the value of a built-in variable can create problems with built-in functions. Exception: i and j are preassigned to 1. One or both of i or j are often reassigned as loop indices. More on this later.
page 21
where expression is a legal combinations of numerical values, mathematical operators, variables, and function calls. The expression can involve: Manual entry Built-in functions that return matrices Custom (user-written) functions that return matrices Loading matrices from text les or mat les
page 23
(1)
As Matlab variables:
>> A = [3 2; 3 1; 1 4] A = 3 2 3 1 1 4 >> x = [5; 7; 9; 2] x = 5 7 9 2 >> v = [9 -3 4 1] v = 9 -3 4 1
page 24
(2)
For manual entry, the elements in a vector are enclosed in square brackets. When creating a row vector, separate elements with a space.
>> v = [7 3 9] v = 7 3 9
page 25
(3)
When assigning elements to matrix, row elements are separated by spaces, and columns are separated by semicolons
>> A = [1 2 3; 5 7 11; 13 17 19] A = 1 2 3 5 7 11 13 17 19
page 26
Transpose Operator
(1)
Once it is created, a variable can be transformed with other operators. The transpose operator converts a row vector to a column vector (and vice versa), and it changes the rows of a matrix to columns.
>> v = [2 4 1 7] v = 2 4 1 >> w = v w = 2 4 1 7
page 27
Transpose Operator
>> A = [1 2 3; 4 5 6; 7 8 9 ] A = 1 2 3 4 5 6 7 8 9 >> B = A B = 1 2 3
(2)
4 5 6
7 8 9
page 28
Overwriting Variables
Once a variable has been created, it can be reassigned
>> x = 2; >> x = x + 2 x = 4 >> y = [1 2 3 4] y = 1 2 3 >> y = y y = 1 2 3 4
NMM: Interactive Computing with Matlab page 29
page 30
(1)
The linspace function creates vectors with elements having uniform linear spacing. Syntax:
x = linspace(startValue,endValue) x = linspace(startValue,endValue,nelements)
Examples:
>> u = linspace(0.0,0.25,5) u = 0 0.0625 0.1250 >> u = linspace(0.0,0.25);
0.1875
0.2500
(2)
page 32
The expressions y = sin(x) and z = cos(x) take advantage of vectorization. If the input to a vectorized function is a vector or matrix, the output is often a vector or matrix having the same shape. More on this later.
NMM: Interactive Computing with Matlab page 33
creates nelements elements between 10startValue and 10endValue. The default value of nelements is 100. Example:
>> w = logspace(1,4,4) w = 10 100
1000
10000
page 34
(1)
create a matrix with a specied diagonal entries, or extract diagonal entries of a matrix create an identity matrix create a matrix lled with ones create a matrix lled with random numbers create a matrix lled with zeros create a row vector of linearly spaced elements create a row vector of logarithmically spaced elements
page 35
(2)
Examples:
>> D = ones(3,3) D = 1 1 1 1 1 1 1 1 1 >> E = ones(2,4) E = 1 1 1 1 1 1
NMM: Interactive Computing with Matlab
1 1
page 36
(3)
ones and zeros are also used to create vectors. To do so, set either nrows or ncols to 1.
>> s = ones(1,4) s = 1 1 1 >> t = zeros(3,1) t = 0 0 0
page 37
(4)
The eye function creates identity matrices of a specied size. It can also create non-square matrices with ones on the main diagonal. Syntax:
A = eye(n) A = eye(nrows,ncols)
Examples:
>> C = eye(5) C = 1 0 0 1 0 0 0 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
page 38
(5)
The optional second input argument to eye allows non-square matrices to be created.
>> D = eye(3,5) D = 1 0 0 1 0 0
0 0 1
0 0 0
0 0 0
page 39
(6)
The diag function can either create a matrix with specied diagonal elements, or extract the diagonal elements from a matrix Syntax:
A = diag(v) v = diag(A)
0 0 3
page 40
(7)
page 41
(8)
The action of the diag function depends on the characteristics and number of the input(s). This polymorphic behavior of Matlab functions is common. Refer to the on-line documentation for the possible variations.
>> A = diag([3 2 1]) A = 3 0 0 0 2 0 0 0 1 >> B = [4 2 2; 3 6 9; 1 1 7]; >> v = diag(B) v = 4 6 7
NMM: Interactive Computing with Matlab
page 42
Subscript Notation
(1)
If A is a matrix, A(i,j) selects the element in the ith row and jth column. Subscript notation can be used on the right hand side of an expression to refer to a matrix element.
>> A = [1 2 3; 4 5 6; 7 8 9]; >> b = A(3,2) b = 8 >> c = A(1,1) c = 1
page 43
Subscript Notation
(1)
page 44
Subscript Notation
(1)
Assigning an element that is beyond the existing dimensions of the matrix causes the matrix to be resized!
>> A = [1 2 3; 4 5 6; 7 8 9]; A = 1 2 3 4 5 6 7 8 9 >> A(4,4) = 11 A = 1 2 4 5 7 8 0 0
3 6 9 0
0 0 0 11
Colon Notation
(1)
Colon notation is very powerful and very important in the eective use of Matlab. The colon is used as both an operator and as a wildcard. Use colon notation to: create vectors refer to or extract ranges of matrix elements
page 46
Colon Notation
Syntax:
startValue:endValue startValue:increment:endValue
(2)
page 47
Colon Notation
Creating row vectors:
>> s = 1:4 s = 1 2
(3)
0.2000
0.3000
0.4000
page 48
Colon Notation
Creating column vectors:
>> u = (1:5) u = 1 2 3 4 5 >> v = 1:5 v = 1 2
(4)
v is a row vector because 1:5 creates a vector between 1 and the transpose of 5.
NMM: Interactive Computing with Matlab page 49
Colon Notation
(5)
page 50
Colon Notation
(6)
page 51
Colon Notation
(7)
Colon notation is often used in compact expressions to obtain results that would otherwise require several steps. Example:
>> A = ones(8,8); >> A(3:6,3:6) = zeros(4,4) A = 1 1 1 1 1 1 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 1 1 1 1 1 1
NMM: Interactive Computing with Matlab
1 1 0 0 0 0 1 1
1 1 0 0 0 0 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
page 52
Colon Notation
(8)
Finally, colon notation is used to convert any vector or matrix to a column vector. Example:
>> x = 1:4; >> y = x(:) y = 1 2 3 4
page 53
Colon Notation
(9)
Colon notation converts a matrix to a column vector by appending the columns of the input matrix
>> A = rand(2,3); >> v = A(:) v = 0.9501 0.2311 0.6068 0.4860 0.8913 0.7621 0.4565 Note: The rand function generates random elements between zero and one. Repeating the preceding statements will, in all likelihood, produce dierent numerical values for the elements of v.
NMM: Interactive Computing with Matlab page 54
page 55
Complex Numbers
Matlab automatically performs complex arithmetic
>> sqrt(-4) ans = 0 + 2.0000i >> x = 1 + 2*i x = 1.0000 + 2.0000i >> y = 1 - 2*i y = 1.0000 - 2.0000i >> z = x*y z = 5
NMM: Interactive Computing with Matlab page 56
(or,
x = 1 + 2*j)
(1)
1.
(i-t = -3,
not -8+i)
page 57
(2)
The i and j variables are often used for array subscripting. Set i (or j) to an integer value that is also a valid array subscript.
>> A = [1 2; 3 4]; >> i = 2; >> A(i,i) = 1 A = 1 2 3 1 >> x = A(2,j) ??? Subscript indices must either be real positive integers or logicals.
Note: When working with complex numbers, it is a good idea to reserve either i or j for the unit imaginary value 1.
NMM: Interactive Computing with Matlab page 58
Euler Notation
(1)
z = e
imaginary iy x real z = ei
page 59
(1)
abs(z) is equivalent to sqrt( real(z)^2 + imag(z)^2 ) Angle of complex number in Euler notation If x is real, If z is complex, conj imag real exp(x) = ex exp(z) = eRe(z)(cos(Im(z) + i sin(Im(z))
Complex conjugate of a number Extract the imaginary part of a complex number Extract the real part of a complex number
page 60
(2)
Strings
Strings are matrices with character elements. String constants are enclosed in single quotes Colon notation and subscript operations apply Examples:
>> first = John; >> last = Coltrane; >> name = [first, ,last] name = John Coltrane >> length(name) ans = 13 >> name(9:13) ans = trane
page 62
(1)
Converts an integer to the character using ASCII codes, or combines characters into a character matrix Finds one string in another string Returns the number of characters in a string Converts a number to string Converts a string to a number Compares two strings Identies rows of a character array that begin with a string Compares the rst n elements of two strings Converts strings and numeric values to a string
page 63
(2)
>> msg1 = [There are ,num2str(100/2.54), inches in a meter] msg1 = There are 39.3701 inches in a meter
For greater control over format of the number-to-string conversion, use sprintf
>> msg2 = sprintf(There are %5.2f cubic inches in a liter,1000/2.54^3) msg2 = There are 61.02 cubic inches in a liter
The Matlab sprintf function is similar to the C function of the same name, but it uses single quotes for the format string.
page 64
(3)
(4)
Use strcmp to test whether two strings are equal, i.e., if they contain the same sequence of characters.
>> msg1 = [There are ,num2str(100/2.54), inches in a meter]; >> msg2 = sprintf(There are %5.2f cubic inches in a liter,1000/2.54^3); >> strcmp(msg1,msg2) ans = 0
The rst nine characters of both strings are There are, so strncmp(msg1,msg2,9) returns 1, or true.
NMM: Interactive Computing with Matlab page 66
(5)
page 67
Polynomials
Matlab polynomials are stored as vectors of coecients. The polynomial coecients are stored in decreasing powers of x Pn(x) = c1xn + c2xn1 + . . . + cnx + cn+1 Example: Evaluate x3 2x + 12 at x = 1.5 Store the coecients of the polynomial in vector c:
>> c = [1 0 -2 12];
Operations performed Product (convolution) of two polynomials Division (deconvolution) of two polynomials Create a polynomial having specied roots Dierentiate a polynomial Evaluate a polynomial Polynomial curve t Find roots of a polynomial
page 69
page 71
page 72
(outer product) 20 18 16 30 27 24
page 73
Vectorization
Vectorization is the use of single, compact expressions that operate on all elements of a vector without explicitly writing the code for a loop. The loop is executed by the Matlab kernel, which is much more ecient at evaluating a loop in interpreted Matlab code. Vectorization allows calculations to be expressed succintly so that programmers get a high level (as opposed to detailed) view of the operations being performed. Vectorization is important to make Matlab operate eciently2.
Recent versions of Matlab have improved the eciency for some non-vectorized code.
page 74
page 75
10
Vectorized Calculations
More examples
>> A = pi*[ 1 2; 3 4] A = 3.1416 6.2832 9.4248 12.5664 >> S = sin(A) S = 0 0 0 0
(6)
3.1416 6.2832
page 77
Array Operators
Array operators support element-by-element operations that are not dened by the rules of linear algebra. Array operators have a period prepended to a standard operator. Symbol .* ./ .\ .^ Operation element-by-element multiplication element-by-element right division element-by-element left division element-by-element exponentiation
Array operators are a very important tool for writing vectorized code.
page 78
(1)
18
0.4000
0.5000
page 79
(1)
page 80
(2)
14 18
18 14
20 8
>> A*B ??? Error using ==> * Inner matrix dimensions must agree.
The last statement causes an error because the number of columns in A is not equal to the number of rows in B a requirement for A and B to be compatible for matrix multiplication.
NMM: Interactive Computing with Matlab page 81
(3)
20 60
The number of columns in A is equal to the number of rows in BT , so A*B is a legal matrix-matrix multiplication. Array operators also apply to matrix powers.
>> A.^2 ans = 1 25
4 36
9 49
16 64
page 82
(1)
All variables dened as the result of entering statements in the command window, exist in the Matlab workspace. At the beginning of a Matlab session, the workspace is empty. Being aware of the workspace allows you to Create, assign, and delete variables Load data from external les Manipulate the Matlab path
page 83
(2)
The clear command deletes variables from the workspace. The who command lists the names of variables in the workspace
>> clear >> who (Delete all variables from the workspace) (No response, no variables are dened after clear) >> a = 5; b = 2; c = 1; >> d(1) = sqrt(b^2 - 4*a*c); >> d(2) = -d(1); >> who Your variables are: a b c d
page 84
(3)
The whos command lists the name, size, memory allocation, and the class of each variables dened in the workspace.
>> whos Name a b c d Size 1x1 1x1 1x1 1x2 Bytes 8 8 8 32 Class double double double double array array array array (complex)
page 85
(4)
The whos command returns the array dimensions, memory requirement and class for each variable in the workspace. Built-in variable classes are double, char, sparse, struct, and cell. The class of a variable determines the type of data that can be stored in it. We will be dealing primarily with numeric data, which is the double class, and occasionally with string data, which is in the char class.
page 86
page 87
page 88
Matlab will only use those functions and data les that are in its path. To add N:\IMAUSER\ME352\PS2 to the path, type
>> p = path; >> path(p,N:\IMAUSER\ME352\PS2);
Matlab version 5 and later has an interactive path editor that makes it easy to adjust the path. The path specication string depends on the operating system. On a Unix/Linux computer a path setting operation might look like:
>> p = path; >> path(p,~/matlab/ME352/ps2);
NMM: Interactive Computing with Matlab page 89
Plotting
Plotting (x, y) data Axis scaling and annotation 2D (contour) and 3D (surface) plotting
page 90
(1)
Two dimensional plots are created with the plot function Syntax:
plot(x,y) plot(xdata,ydata,symbol) plot(x1,y1,x2,y2,...) plot(x1,y1,symbol1,x2,y2,symbol2,...)
Note: x and y must have the same shape, x1 and y1 must have the same shape, x2 and y2 must have the same shape, etc.
page 91
(2)
page 92
(1)
The curves for a data set are drawn from combinations of the color, symbol, and line types in the following table.
Color y m c r g b w k yellow cyan red green blue white black . x + * s d v point circle x-mark plus star square diamond triangle (down) magenta o Symbols ^ < > p h triangle (up) triangle (left) triangle (right) pentagram hexagram : -. -Line solid dotted dashdot dashed
(2)
Put black diamonds at each data point and connect the diamonds with black dashed lines:
plot(x,y,kd--)
page 94
(1)
Combinations of linear and logarithmic scaling are obtained with functions that, other than their name, have the same syntax as the plot function. Name loglog plot semilogx semilogy Axis scaling log10(y) versus log10(x) linear y versus x linear y versus log10(x) log10(y) versus linear x
Note: As expected, use of logarithmic axis scaling for data sets with negative or zero values results in a error. Matlab will complain and then plot only the positive (nonzero) data.
NMM: Interactive Computing with Matlab page 95
(2)
>> semilogy(x,y);
10 10 10 10
-1
-2
page 96
(1)
The subplot function is used to create a matrix of plots in a single gure window. Syntax:
subplot(nrows,ncols,thisPlot)
Repeat the values of nrows and ncols for all plots in a single gure window. Increment thisPlot for each plot
page 97
(1)
title(sin(x));
title(sin(2x));
title(sin(3x));
title(sin(4x));
page 98
(2)
page 99
Plot Annotation
Operation(s) performed Reset axis limits Draw grid lines at the major ticks marks on the x and y axes Add text to a location determined by a mouse click Create a legend to identify symbols and line types when multiple curves are drawn on the same plot Add text to a specied (x, y) location Label the x-axis Label the y -axis Add a title above the plot
page 100
(1)
T = D(:,2:4);
plot(m,t(:,1),ro,m,T(:,2),k+,m,T(:,3),b-); xlabel(Month); ylabel(Temperature ({}^\circ F)); title(Monthly average temperature at PDX); axis([1 12 20 100]); legend(High,Low,Average,2);
Note: The pdxTemp.dat le is in the data directory of the NMM toolbox. Make sure the toolbox is installed and is included in the Matlab path.
(See next slide for the plot.)
NMM: Interactive Computing with Matlab page 101
(2)
Monthly average temperature for Portland International Airport High Low Average
6 Month
10
12
page 102