Professional Documents
Culture Documents
Interactive Computing
with Matlab
• Basic Matlab Operations
Gerald W. Recktenwald Starting Matlab
Using Matlab as a calculator
Department of Mechanical Engineering Introduction to variables and functions
Portland State University
• Matrices and Vectors: All variables are matrices.
gerry@me.pdx.edu
Creating matrices and vectors
Subscript notation
Colon notation
• Additional Types of Variables
Complex numbers
These slides are a supplement to the book Numerical Methods with Strings
Matlab: Implementations and Applications, by Gerald W. Recktenwald, Polynomials
c 2002, Prentice-Hall, Upper Saddle River, NJ. These slides are c
2002 Gerald W. Recktenwald. The PDF version of these slides may • Working with Matrices and Vectors
be downloaded or stored or printed only for noncommercial, educational Linear algebra
use. The repackaging or sale of these slides in any form, without written
Vectorized operations
consent of the author, is prohibited.
Array operators
The latest version of this PDF file, along with other supplemental material
for the book, can be found at www.prenhall.com/recktenwald. • Managing the Interactive Environment
• Plotting
Version 1.02 October 2, 2002
NMM: Interactive Computing with Matlab page 2 NMM: Interactive Computing with Matlab page 3
Matlab Workspace (version 6) Matlab as a Calculator
>> ans/2
ans =
2
>> a = 5
a =
5
>> b = 6
b =
Launch Pad/Workspace: Command History/Current Directory:
Used to browse documentation, 6
Used to view and re-enter typed commands,
or view values of variables in or change directories
the workspace >> c = b/a
c =
1.2000
NMM: Interactive Computing with Matlab page 4 NMM: Interactive Computing with Matlab page 5
pi (= π ) and ans are a built-in variables Many standard mathematical functions, such as sin, cos, log,
and log10, are built-in
>> pi
ans = >> log(256)
3.1416 ans =
5.5452
>> sin(ans/4)
ans = >> log10(256)
0.7071 ans =
2.4082
Note: There is no “degrees” mode. All angles are measured >> log2(256)
ans =
in radians. 8
NMM: Interactive Computing with Matlab page 6 NMM: Interactive Computing with Matlab page 7
Looking for Functions Ways to Get Help
Syntax:
• Use on-line help to request info on a specific function
lookfor string >> help sqrt
NMM: Interactive Computing with Matlab page 8 NMM: Interactive Computing with Matlab page 9
See also LOG2, LOG10, EXP, LOGM. Type variable name and omit the semicolon to print the value of
a variable (that is already defined)
>> y
y =
7.6811 ( = log(sqrt(59)) + 5^0.25 )
NMM: Interactive Computing with Matlab page 10 NMM: Interactive Computing with Matlab page 11
Multiple Statements per Line Matlab Variables Names
Use commas or semicolons to enter more than one statement at Legal variable names:
once. Commas allow multiple statements per line without
suppressing output. • Begin with one of a–z or A–Z
• Have remaining characters chosen from a–z, A–Z, 0–9, or
>> a = 5; b = sin(a), c = cosh(a) • Have a maximum length of 31 characters
b = • Should not be the name of a built-in variable, built-in
-0.9589 function, or user-defined function
c =
74.2099 Examples:
xxxxxxxxx
pipeRadius
widgets_per_baubble
mySum
mysum
NMM: Interactive Computing with Matlab page 12 NMM: Interactive Computing with Matlab page 13
Name Meaning
All Matlab variables are matrices
ans value of an expression when that expression
is not assigned to a variable
A Matlab vector is a matrix with one row or one column
eps floating point precision
A Matlab scalar is a matrix with one row and one column
pi π, (3.141492 . . .)
realmax largest positive floating point number
realmin smallest positive floating point number Overview of Working with matrices and vectors
Inf ∞, a number larger than realmax,
the result of evaluating 1/0. • Creating vectors:
NaN not a number, the result of evaluating 0/0 linspace and logspace
• Creating matrices:
ones, zeros, eye, diag, . . .
Rule: Only use built-in variables on the right hand side of an • Subscript notation
expression. Reassigning the value of a built-in variable • Colon notation
can create problems with built-in functions. • Vectorization
√
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
NMM: Interactive Computing with Matlab page 14 NMM: Interactive Computing with Matlab page 15
Creating Matlab Variables Manual Entry
Matlab variables are created with an assignment statement For manual entry, the elements in a vector are enclosed in square
brackets. When creating a row vector, separate elements with a
>> x = expression space.
NMM: Interactive Computing with Matlab page 16 NMM: Interactive Computing with Matlab page 17
Once it is created, a variable can be transformed with other Once a variable has been created, it can be reassigned
operators. The transpose operator converts a row vector to a
column vector (and vice versa), and it changes the rows of a >> x = 2;
matrix to columns. >> x = x + 2
x =
>> v = [2 4 1 7] 4
v =
2 4 1 7 >> y = [1 2 3 4]
y =
>> v’ 1 2 3 4
ans =
2 >> y = y’
4 y =
1 1
7 2
3
>> A = [1 2 3; 4 5 6; 7 8 9 ] 4
A =
1 2 3
4 5 6
7 8 9
>> A’
ans =
1 4 7
2 5 8
3 6 9
NMM: Interactive Computing with Matlab page 18 NMM: Interactive Computing with Matlab page 19
Creating vectors with linspace Example: A Table of Trig Functions
The linspace function creates vectors with elements having >> x = linspace(0,2*pi,6)’; (note transpose)
uniform linear spacing. >> y = sin(x);
>> z = cos(x);
Syntax: >> [x y z]
x = linspace(startValue,endValue) ans =
x = linspace(startValue,endValue,nelements) 0 0 1.0000
1.2566 0.9511 0.3090
2.5133 0.5878 -0.8090
Examples: 3.7699 -0.5878 -0.8090
>> u = linspace(0.0,0.25,5) 5.0265 -0.9511 0.3090
u = 6.2832 0 1.0000
0 0.0625 0.1250 0.1875 0.2500
>> u = linspace(0.0,0.25);
The expressions y = sin(x) and z = cos(x) take advantage
>> v = linspace(0,9,4)’ of vectorization. If the input to a vectorized function is a vector
v = or matrix, the output is often a vector or matrix having the same
0 shape. More on this later.
3
6
9
NMM: Interactive Computing with Matlab page 20 NMM: Interactive Computing with Matlab page 21
The logspace function creates vectors with elements having Name Operation(s) Performed
uniform logarithmic spacing. diag create a matrix with a specified diagonal entries,
or extract diagonal entries of a matrix
Syntax:
eye create an identity matrix
x = logspace(startValue,endValue)
ones create a matrix filled with ones
x = logspace(startValue,endValue,nelements)
rand create a matrix filled with random numbers
creates nelements elements between 10startValue and zeros create a matrix filled with zeros
10endValue. The default value of nelements is 100. linspace create a row vector of linearly spaced elements
logspace create a row vector of logarithmically spaced
Example:
elements
>> w = logspace(1,4,4)
w =
10 100 1000 10000
NMM: Interactive Computing with Matlab page 22 NMM: Interactive Computing with Matlab page 23
Functions to Create Matrices (2) Functions to Create Matrices (3)
Use ones and zeros to set intial values of a matrix or vector. ones and zeros are also used to create vectors. To do so, set
either nrows or ncols to 1.
Syntax:
A = ones(nrows,ncols) >> s = ones(1,4)
A = zeros(nrows,ncols) s =
1 1 1 1
>> E = ones(2,4)
E =
1 1 1 1
1 1 1 1
NMM: Interactive Computing with Matlab page 24 NMM: Interactive Computing with Matlab page 25
The eye function creates identity matrices of a specified size. It The diag function can either create a matrix with specified
can also create non-square matrices with ones on the main diagonal elements, or extract the diagonal elements from a
diagonal. matrix
Syntax: Syntax:
A = eye(n) A = diag(v)
A = eye(nrows,ncols) v = diag(A)
Examples: Example:
>> C = eye(5) Use diag to create a matrix
C =
1 0 0 0 0 >> v = [1 2 3];
0 1 0 0 0 >> A = diag(v)
0 0 1 0 0 A =
0 0 0 1 0 1 0 0
0 0 0 0 1 0 2 0
0 0 3
>> D = eye(3,5)
D =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
NMM: Interactive Computing with Matlab page 26 NMM: Interactive Computing with Matlab page 27
Functions to Create Matrices (6) Subscript Notation (1)
Example: If A is a matrix, A(i,j) selects the element in the ith row and
Use diag to extract the diagonal of a matrix jth column. Subscript notation can be used on the right hand
side of an expression to refer to a matrix element.
>> B = [1:4; 5:8; 9:12]
B = >> A = [1 2 3; 4 5 6; 7 8 9];
1 2 3 4 >> b = A(3,2)
5 6 7 8 b =
9 10 11 12 8
NMM: Interactive Computing with Matlab page 28 NMM: Interactive Computing with Matlab page 29
Referring to elements outside of current matrix dimensions Colon notation is very powerful and very important in the
results in an error effective use of Matlab. The colon is used as both an operator
and as a wildcard.
>> A = [1 2 3; 4 5 6; 7 8 9];
>> A(1,4)
??? Index exceeds matrix dimensions.
Use colon notation to:
• create vectors
Assigning an elements outside of current matrix dimensions • refer to or extract ranges of matrix elements
causes the matrix to be resized!
NMM: Interactive Computing with Matlab page 30 NMM: Interactive Computing with Matlab page 31
Colon Notation (2) Colon Notation (3)
Creating row vectors: Use colon as a wildcard to refer to an entire column or row
NMM: Interactive Computing with Matlab page 32 NMM: Interactive Computing with Matlab page 33
Note: The rand function generates random elements between zero and
one. Repeating the preceding statements will, in all likelihood,
produce different numerical values for the elements of v.
NMM: Interactive Computing with Matlab page 34 NMM: Interactive Computing with Matlab page 35
Additional Types of Variables Complex Numbers
The basic Matlab variable is a matrix — a two dimensional Matlab automatically performs complex arithmetic
array of values. The elements of a matrix variable can either be
numeric values or characters. If the elements are numeric values >> sqrt(-4)
ans =
they can either be real or complex (imaginary).
0 + 2.0000i
More general variable types are available: n-dimensional arrays >> x = 1 + 2*i (or, x = 1 + 2*j)
(where n > 2), structs, cell arrays, and objects. Numeric (real x =
and complex) and string arrays of dimension two or less will be 1.0000 + 2.0000i
sufficient for our purposes.
>> y = 1 - 2*i
y =
1.0000 - 2.0000i
We now consider some simple variations on numeric and string
matrices: >> z = x*y
z =
5
• Complex Numbers
• Strings
• Polynomials
NMM: Interactive Computing with Matlab page 36 NMM: Interactive Computing with Matlab page 37
>> i = 5;
>> t = 8; imaginary
>> u = sqrt(i-t) (i-t = -3, not -8+i)
u = iy z = ζ eiθ
0 + 1.7321i ζ
>> u*u
ans =
θ
-3.0000 x real
>> A = [1 2; 3 4];
>> i = 2;
>> A(i,i) = 1
A =
1 2
3 1
NMM: Interactive Computing with Matlab page 38 NMM: Interactive Computing with Matlab page 39
Functions for Complex Arithmetic (1) Functions for Complex Arithmetic (2)
>> angle(z)*180/pi
Note: When working with complex numbers, it is a good ans =
idea to√reserve either i or j for the unit imaginary 60.0000
value −1.
NMM: Interactive Computing with Matlab page 40 NMM: Interactive Computing with Matlab page 41
Function Operation
• Strings are matrices with character elements.
char convert an integer to the character using ASCII codes,
• String constants are enclosed in single quotes
or combine characters into a character matrix
• Colon notation and subscript operations apply
findstr finds one string in another string
length returns the number of characters in a string
Examples: num2str converts a number to string
>> first = ’John’; str2num converts a string to a number
>> last = ’Coltrane’;
strcmp compares two strings
>> name = [first,’ ’,last]
name = strmatch identifies rows of a character array that begin
John Coltrane with a string
>> name(9:13)
ans =
trane
NMM: Interactive Computing with Matlab page 42 NMM: Interactive Computing with Matlab page 43
Functions for String Manipulation (2) Polynomials
>> findstr(’in’,msg1)
ans =
19 26
NMM: Interactive Computing with Matlab page 44 NMM: Interactive Computing with Matlab page 45
NMM: Interactive Computing with Matlab page 46 NMM: Interactive Computing with Matlab page 47
Vector Addition and Subtraction Vector Inner and Outer Products
Vector and addition and subtraction are element-by-element The inner product combines two vectors to form a scalar
operations.
T
σ = u · v = u v ⇐⇒ σ = ui v i
Example:
>> u = [10 9 8]; (u and v are row vectors) The outer product combines two vectors to form a matrix
>> v = [1 2 3];
T
>> u+v A = u v ⇐⇒ ai,j = ui vj
ans =
11 11 11
>> u-v
ans =
9 7 5
NMM: Interactive Computing with Matlab page 48 NMM: Interactive Computing with Matlab page 49
NMM: Interactive Computing with Matlab page 50 NMM: Interactive Computing with Matlab page 51
Vectorization of Built-in Functions Vector Calculations (3)
Most built-in function support vectorized operations. If the input More examples
is a scalar the result is a scalar. If the input is a vector or matrix,
the output is a vector or matrix with the same number of rows >> A = pi*[ 1 2; 3 4]
and columns as the input. A =
3.1416 6.2832
9.4248 12.5664
Example:
>> x = 0:pi/4:pi (define a row vector) >> S = sin(A)
x = S =
0 0.7854 1.5708 2.3562 3.1416 0 0
0 0
>> y = cos(x) (evaluate cosine of each x(i)
y = >> B = A/2
1.0000 0.7071 0 -0.7071 -1.0000 B =
1.5708 3.1416
4.7124 6.2832
Contrast with Fortran implementation:
>> T = sin(B)
real x(5),y(5) T =
pi = 3.14159624 1 0
dx = pi/4.0 -1 0
do 10 i=1,5
x(i) = (i-1)*dx
y(i) = sin(x(i))
10 continue
NMM: Interactive Computing with Matlab page 52 NMM: Interactive Computing with Matlab page 53
Array operators are a very important tool for writing vectorized >> z = sin(pi*u/2) ./ cos(pi*v/2)
code.
Warning: Divide by zero.
z =
1 NaN 1
NMM: Interactive Computing with Matlab page 54 NMM: Interactive Computing with Matlab page 55
Using Array Operators (2) The Matlab Workspace (1)
>> A*B’
ans =
60 20
164 60
>> A.^2
ans =
1 4 9 16
25 36 49 64
NMM: Interactive Computing with Matlab page 56 NMM: Interactive Computing with Matlab page 57
The clear command deletes variables from the workspace. The The whos command lists the name, size, memory allocation, and
who command lists the names of variables in the workspace the class of each variables defined in the workspace.
>> clear (Delete all variables from the workspace) >> whos
>> who
(No response, no variables are defined after ‘clear’) Name Size Bytes Class
NMM: Interactive Computing with Matlab page 58 NMM: Interactive Computing with Matlab page 59
Working with External Data Files Loading Data from External File
load fileName
load fileName matrixVariable
NMM: Interactive Computing with Matlab page 60 NMM: Interactive Computing with Matlab page 61
Matlab will only use those functions and data files that are in
• Plotting (x, y) data
its path.
• Axis scaling and annotation
• 2D (contour) and 3D (surface) plotting
To add N:\IMAUSER\ME352\PS2 to the path, type
>> p = path;
>> path(p,’N:\IMAUSER\ME352\PS2’);
>> p = path;
>> path(p,’~/matlab/ME352/ps2’);
NMM: Interactive Computing with Matlab page 62 NMM: Interactive Computing with Matlab page 63
Plotting (x, y) Data (1) Plotting (x, y) Data (2)
Two dimensional plots are created with the plot function Example:
A simple line plot
Syntax:
plot(x,y) >> x = linspace(0,2*pi);
plot(xdata,ydata,symbol) >> y = sin(x);
plot(x1,y1,x2,y2,...) >> plot(x,y);
plot(x1,y1,symbol1,x2,y2,symbol2,...)
-0.5
-1
0 2 4 6 8
NMM: Interactive Computing with Matlab page 64 NMM: Interactive Computing with Matlab page 65
Line and Symbol Types (1) Line and Symbol Types (2)
The curves for a data set are drawn from combinations of the Examples:
color, symbol, and line types in the following table. Put yellow circles at the data points:
NMM: Interactive Computing with Matlab page 66 NMM: Interactive Computing with Matlab page 67
Alternative Axis Scaling (1) Alternative Axis Scaling (2)
2
semilogy log10(y) versus linear x
0
0 1 2 3
-1
10
-2
10
0 1 2 3
NMM: Interactive Computing with Matlab page 68 NMM: Interactive Computing with Matlab page 69
Multiple plots per figure window (1) Multiple plots per figure window (2)
sin(x) sin(2x)
The subplot function is used to create a matrix of plots in a 1.5 1.5
single figure window. 1 1
0.5 0.5
Syntax: 0 0
>> subplot(2,2,3);
>> plot(x,sin(3*x)); axis([0 2*pi -1.5 1.5]); title(’sin(3x)’);
>> subplot(2,2,4);
>> plot(x,sin(4*x)); axis([0 2*pi -1.5 1.5]); title(’sin(4x)’);
NMM: Interactive Computing with Matlab page 70 NMM: Interactive Computing with Matlab page 71
Plot Annotation Plot Annotation Example
Temperature ( F)
text Add text to a specified (x, y) location 70
°
60
xlabel Label the x-axis
50
20
2 4 6 8 10 12
Month
NMM: Interactive Computing with Matlab page 72 NMM: Interactive Computing with Matlab page 73