Baixe Matlab - ingles e outras Manuais, Projetos, Pesquisas em PDF para Matemática, somente na Docsity!
Interactive Computing
with
Matlab
Gerald W. Recktenwald
Department of Mechanical Engineering
These slides are a supplement to the book
Numerical Methods with
Matlab: Implementations and Applications
, by Gerald W. Recktenwald,
c©^ 2000–2006, Prentice-Hall, Upper Saddle River, NJ. These slides arecopyright^ c©
2000–2006 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 file, along with other supplemental materialfor the book, can be found at
www.prenhall.com/recktenwald
or
web.cecs.pdx.edu/~gerry/nmm/
. Version 1.
August 21, 2006
Overview
•^ 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 NMM: Interactive Computing with
Matlab^
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^
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:^ >>
for full version EDU>^ for educational version
-^ Matlab
responds to commands by printing text in the command
window, or by opening a
figure window
for graphical output.
-^ Toggle between windows by clicking on them with the mouse. NMM: Interactive Computing with
Matlab^
page 4
Matlab
Desktop
Recent Directory Menu: Used to change currentworking directory.
Launch Pad/Workspace: Used to browse documentation,or view values of variables inthe workspace
Command Prompt: Enter typed commands here.Text results are displayed here. Command History/CurrentDirectory:
View and re-enter Select Launch Pad tab orWorkspace tabpreviously typed commands,or change directories Select Command History tabor Current Directory tab NMM: Interactive Computing with
Matlab^
Matlab
Desktop
-^ The desktop provides different 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 • Watch an animated demonstration of the
Matlab
desktop by typing
playbackdemo(’desktop’) at the command prompt. NMM: Interactive Computing with
Matlab^
page 6
Matlab
as a Calculator
Enter formulas at the command prompt^ >> 2 + 6 - 4
(press^ return
after ‘‘4’’)
ans =^4 >> ans/2ans =^2 NMM: Interactive Computing with
Matlab^
On-line Help
Syntax:^ help
functionName
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
The help browser opens when you type a
doc^ command:
doc plot NMM: Interactive Computing with
Matlab^
Looking for Functions
Syntax:^ lookfor
string
searches first line of function descriptions for “
string
Example:^ >> lookfor cosine produces^ ACOS
Inverse cosine.ACOSH^ Inverse hyperbolic cosine.COS Cosine.COSH Hyperbolic cosine. NMM: Interactive Computing with
Matlab^
page 14
Strategies for Interactive Computing
-^ Use the command window for short sequences of calculations •^ Later we’ll learn how to build reusable functions for more complex tasks. •^ The command window is good for testing ideas and running sequencesof operations contained in functions •^ Any command executed in the command window can also be used in afunction.Let’s continue with a tour of interactive computing. NMM: Interactive Computing with
Matlab^
Suppress Output with Semicolon
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.25z =
NMM: Interactive Computing with
Matlab^
page 16
Suppress Output with Semicolon
Type variable name and omit the semicolon to print the value of a variable(that is already defined)^ >> x = 5;>> y = sqrt(59);>> z = log(y) + x^0.25z =
yy =
( = log(sqrt(59)) + 5^0.25 )
NMM: Interactive Computing with
Matlab^
Multiple Statements per Line
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),
c = cosh(a)
b =-0.9589c =74.2099 NMM: Interactive Computing with
Matlab^
page 18
Matlab
Variables Names
Legal variable names:^ •^ Begin with one of a–z or A–Z^ •^ Have remaining characters chosen from a–z, A–Z, 0–9, or^ •^ Have a maximum length of 31 characters^ •^ Should not be the name of a built-in variable, built-in function, oruser-defined function Examples:
xxxxxxxxxpipeRadiuswidgets_per_boxmySummysum
Note:^
mySum^
and^ mysum
are^ different
variables.
Matlab
is^ case
sensitive
NMM: Interactive Computing with
Matlab^
Element-by-Element Creation of Matrices and Vectors
A^ matrix,
a^ column
vector,
and a row vector:
A =
3 2 3 1 1 4 5 7 x = 9 2
[ v = 9
−^3
] 4 1
As^ Matlab
variables:
>> A = [3 2; 3 1; 1 4]A =^3
x = [5; 7; 9; 2]x =^5792 >> v = [9 -3 4 1]v =^9
NMM: Interactive Computing with
Matlab^
page 24
Element-by-Element Creation of Matrices and Vectors
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 =
Separate columns with a semicolon^ >> w = [2; 6; 1]w =
NMM: Interactive Computing with
Matlab^
page 25
Element-by-Element Creation of Matrices and Vectors
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 =
NMM: Interactive Computing with
Matlab^
page 26
Transpose Operator
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 =
w = v’w =^2417 NMM: Interactive Computing with
Matlab^
page 27
Transpose Operator
>> A = [1 2 3; 4 5 6; 7 8 9 ]A =^1
>> B = A’B =^1
NMM: Interactive Computing with
Matlab^
page 28
Overwriting Variables
Once a variable has been created, it can be reassigned^ >> x = 2;>> x = x + 2x =
(^4) >> y = [1 2 3 4]y =^1
y = y’y =^1234 NMM: Interactive Computing with
Matlab^
Using Functions to Create Matrices and Vectors Create vectors with built-in functions: linspace
and^ logspace
Create matrices with built-in functions:^ ones
,^ zeros
,^ eye,^
diag,...
Note that
ones^
and^ zeros
can also be used to create vectors.
NMM: Interactive Computing with
Matlab^
page 30
Creating vectors with
linspace
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 =
>> u = linspace(0.0,0.25); Remember: Ending a statement with semicolon suppresses the output. NMM: Interactive Computing with
Matlab^
Functions to Create Matrices
Use^ ones
and^ zeros
to set intial values of a matrix or vector.
Syntax:^ A^ = ones(
nrows,
ncols) A^ = zeros(
nrows,
ncols)
Examples:^ >> D = ones(3,3)D =
E = ones(2,4)E =^1
NMM: Interactive Computing with
Matlab^
page 36
Functions to Create Matrices
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
t = zeros(3,1)t =^000 NMM: Interactive Computing with
Matlab^
Functions to Create Matrices
The^ eye
function creates identity matrices of a specified 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 =
NMM: Interactive Computing with
Matlab^
page 38
Functions to Create Matrices
The optional second input argument to
eye^ allows non-square matrices to
be created.^ >> D = eye(3,5)D =
where^
D= 1i,j^
whenever
i^ =^ j.
NMM: Interactive Computing with
Matlab^
Functions to Create Matrices
The^ diag
function can
either
create a matrix with specified diagonal
elements,
or^ extract the diagonal elements from a matrix
Syntax:^ A^ = diag(
v)
v^ = diag(A) Example:
Use^
diag^ to create a matrix
v = [1 2 3];>> A = diag(v)A =^1
NMM: Interactive Computing with
Matlab^
page 40
Functions to Create Matrices
Example:
Use^
diag^ to extract the diagonal of a matrix
>> B = [1:4; 5:8; 9:12]B =^1
w = diag(B)w =^1611 NMM: Interactive Computing with
Matlab^
Functions to Create Matrices
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])
Create a matrix with a specified diagonal
A =^3
B = [4 2 2; 3 6 9; 1 1 7];>> v = diag(B)
Extract the diagonal of a matrix
v =^467 NMM: Interactive Computing with
Matlab^
page 42
Subscript Notation
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 torefer 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 NMM: Interactive Computing with
Matlab^
Colon Notation
Creating row vectors:^ >> s = 1:4s =
t = 0:0.1:0.4t =
NMM: Interactive Computing with
Matlab^
page 48
Colon Notation
Creating column vectors:^ >> u = (1:5)’u =
(^12345) >> v = 1:5’v = 1 2
v^ is a row vector because
1:5’^
creates a vector between 1 and the
transpose of 5. NMM: Interactive Computing with
Matlab^
Colon Notation
Use colon as a wildcard to refer to an entire column or row^ >> A = [1 2 3; 4 5 6; 7 8 9];>> A(:,1)ans =
(^147) >> A(2,:)ans = 4 5
NMM: Interactive Computing with
Matlab^
page 50
Colon Notation
Or use colon notation to refer to subsets of columns or rows^ >> A(2:3,1)ans =
(^47) >> A(1:2,2:3)ans =ans = 2 35 6 NMM: Interactive Computing with
Matlab^
Colon Notation
Colon notation is often used in compact expressions to obtain results thatwould otherwise require several steps. Example:^ >> A = ones(8,8);>> A(3:6,3:6) = zeros(4,4)A =
NMM: Interactive Computing with
Matlab^
page 52
Colon Notation
Finally, colon notation is used to convert any vector or matrix to a columnvector. Example:^ >> x = 1:4;>> y = x(:)y =
NMM: Interactive Computing with
Matlab^
Colon Notation
Colon notation converts a matrix to a column vector by appending thecolumns of the input matrix^ >> A = rand(2,3);>> v = A(:)v =
Note:^
The^ rand
function generates random elements between zero and one. Repeating the preceding statements will, in all likelihood, produce differentnumerical values for the elements of
v.
NMM: Interactive Computing with
Matlab^
page 54
Additional Types of Variables
Matrix elements can either be numeric values or characters. Numericelements can either be real or complex (imaginary).More general variable types are available:
n-dimensional arrays (where
n >^2 ), structs, cell arrays, and objects. Numeric (real and complex) andstring arrays of dimension two or less will be sufficient for our purposes.Consider some simple variations on numeric and string matrices:^ •^ Complex Numbers^ •^ Strings^ •^ Polynomials NMM: Interactive Computing with
Matlab^
Functions for Complex Arithmetic
Function
Operation abs^
Compute the magnitude of a number^ abs(z)
is equivalent to
sqrt( real(z)^2 + imag(z)^2 )
angle^
Angle of complex number in Euler notation exp^
If^ x^ is real,
exp(x) =
x e
If^ z^ is complex,
exp(z)
Re(z) = e
(cos(Im(
z) +^ i^ sin(Im(
z))
conj^
Complex conjugate of a number imag^
Extract the imaginary part of a complex number real^
Extract the real part of a complex number NMM: Interactive Computing with
Matlab^
page 60
Functions for Complex Arithmetic
Examples:^ >> zeta = 5;
theta = pi/3;
z = zetaexp(itheta)z =2.5000 + 4.3301i>> abs(z)ans =^5 >> sqrt(z*conj(z))ans =^5
x = real(z)x =2.5000>> y = imag(z)y =4.3301>> angle(z)*180/pians =60.
Remember:
There is no “degrees” mode in
Matlab
. All angles are in radians.
NMM: Interactive Computing with
Matlab^
Strings
-^ Strings are matrices withcharacter elements. •^ String constants are enclosed insingle quotes •^ Colon notation and subscriptoperations apply
Examples:^ >> first = ’John’;>> last
= ’Coltrane’;
name
= [first,’ ’,last] name =John Coltrane>> length(name)ans =^13 >> name(9:13)ans =trane
NMM: Interactive Computing with
Matlab^
page 62
Functions for String Manipulation
Function
Operation char^
Converts an integer to the character using ASCII codes, orcombines characters into a character matrix findstr
Finds one string in another string length^
Returns the number of characters in a string num2str
Converts a number to string str2num
Converts a string to a number strcmp^
Compares two strings strmatch
Identifies rows of a character array that begin with a string strncmp
Compares the first
n^ elements of two strings
sprintf
Converts strings and numeric values to a string NMM: Interactive Computing with
Matlab^
Functions for String Manipulation
num2str
converts a number to a string
>> 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. NMM: Interactive Computing with
Matlab^
page 64
Functions for String Manipulation
The^ char
function can be used to combine strings
>> both = char(msg1,msg2)both =There are 39.3701 inches in a meterThere are 61.02 cubic inches in a liter or to refer to individual characters by their ASCII codes
1
char(49)ans = 1 >> char([77 65 84 76 65 66])ans =MATLAB 1 See e.g.,,
www.asciicodes.com
or^ wikipedia.org/wiki/ASCII
.
NMM: Interactive Computing with
Matlab^
Functions for String Manipulation
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 =
Compare the first
n^ characters of two strings with
strncmp
>> strncmp(msg1,msg2,9)ans =^1 The first nine characters of both strings are “
There are
”, so
strncmp(msg1,msg2,9)
returns 1, or
true.
NMM: Interactive Computing with
Matlab^
page 66
Functions for String Manipulation
Locate occurances of one string in another string with
findstr
findstr(’in’,msg1)ans =^19
msg1(19:20)ans =in NMM: Interactive Computing with
Matlab^
Vector Inner and Outer Products
The inner product combines two vectors to form a scalar
σ^ =^ u^
·^ v^ =^ u v
T^ ⇐⇒
uvi^ i
The outer product combines two vectors to form a matrix
A^ =^ u
T^ v^ ⇐⇒
a=i,j^
uvi^ j
NMM: Interactive Computing with
Matlab^
page 72
Inner and Outer Products in
Matlab
Inner and outer products are supported in
Matlab
as natural extensions
of the multiplication operator^ >> u = [10 9 8];
(u^ and^
v^ are row vectors)
v = [1 2 3];>> u*v’
(inner product)
ans =^52 >> u’*v
(outer product)
ans =^10
NMM: Interactive Computing with
Matlab^
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
efficient at evaluating a loop in interpreted
Matlab
code.
-^ Vectorization allows calculations to be expressed succintly so thatprogrammers get a high level (as opposed to detailed) view of theoperations being performed. •^ Vectorization is important to make
Matlab
operate efficiently
2 Recent versions of
Matlab
have improved the efficiency for some non-vectorized code.
NMM: Interactive Computing with
Matlab^
page 74
Vectorization of Built-in Functions
Most built-in function support
vectorized
operations. If the input is a
scalar the result is a scalar. If the input is a vector or matrix, the output isa vector or matrix with the same number of rows and columns as the input. Example:^ >> x = 0:pi/4:pi
(define a row vector)
x =
y = cos(x)
(evaluate cosine of each
x(i))
y =1.
NMM: Interactive Computing with
Matlab^
Contrast with FORTRAN Implementation
The^ Matlab
statements
x = 0:pi/4:pi;y = cos(x); are equivalent to the following FORTRAN code^ real x(5),y(5)pi = 3.14159624dx = pi/4.0do 10 i=1,
x(i) = (i-1)*dxy(i) = sin(x(i))
10 continue No explicit loop is necessary in
Matlab
NMM: Interactive Computing with
Matlab^
page 76
Vectorized Calculations
More examples^ >> A = pi*[ 1 2; 3 4]A =
3.^
9.^
S = sin(A)S =^0
>> B = A/2B =1.
T = sin(B)T =^1
-^
NMM: Interactive Computing with
Matlab^
Array Operators
Array operators support element-by-element operations that are notdefined 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. NMM: Interactive Computing with
Matlab^
page 78
Using Array Operators
Examples:
Element-by-element multiplication and division
>> u = [1 2 3];>> v = [4 5 6]; Use^ .*^ and
./^ for element-by-element multiplication and division
w = u.*vw =^4
x = u./vx =0.
NMM: Interactive Computing with
Matlab^