Transcript Lecture-6

(What Are Strings?)
A string is an array of characters
Strings have many uses in MATLAB
• Display text output
• Specify formatting for plots
• Input arguments for some functions
• Text input from user or data files
1
(Creating Strings)
• We create a string by typing characters within single quotes
(').
 Many programming languages use the quotation mark (")
for strings. Not MATLAB!
• Strings can have letters, digits, symbols, spaces.
 To type single quote in string, use two consecutive single
quotes, e.g., make the string of English "Greg's car" by
typing
'"Greg''s car"'
'ad ef', '3%fr2', '{edcba:21!',
'MATLAB'
 Examples:
2
You can assign string to a variable, just like
numbers.
>> name = 'Sting'
name =
Sting
>> police = 'New York''s finest'
police =
New York's finest
3
In a string variable
• Numbers are stored as an array
• A one-line string is a row vector
 Number of elements in vector is number of
characters in string
>> name = 'Howard the Duck';
>> size( name )
ans =
1 15
4
Strings are indexed the same way as
vectors and matrices
• Can read by index
• Can write by index
• Can delete by index
5
Example:
>> word = 'dale';
>> word(1)
ans = d
>> word(1) = 'v'
word = vale
>> word(end) = []
word = val
>> word(end+1:end+3) = 'ley'
word = valley
6
7
MATLAB stores strings with multiple lines
as an array. This means each line must
have the same number of columns
(characters).
>> names = [ 'Greg'; 'John' ]
names =
Greg
John
>> size( names )
ans =
2 4
8
Problem
4 characters
3 characters
>> names = [ 'Greg'; 'Jon' ]???
Error using ==> vertcat
CAT arguments dimensions are not
consistent.
Must put in extra characters (usually spaces) by
hand so that all rows have same number of
characters
>> names = [ 'Greg'; 'Jon ' ]
Greg
Extra space
Jon
9
(String Padding)
Making sure each line of text has the same number of
characters is a big pain. MATLAB solves problem with char
function, which pads each line on the right with enough spaces
so that all lines have the same number of characters.
>> question=char('Romeo, Romeo,','Wherefore art thou', 'Romeo?')
question =
Romeo, Romeo,
Wherefore art thou
Romeo?
>> size (question)
ans =
3 18
10
R o m e o ,
W h e r
e f
R o m e
o ?
R o m e o ,
o r
e
a
r
t
t
h o u
Three lines of text stored in a 3x18 array.
MATLAB makes all rows as long as
longest row.
First and third rows above have enough
space characters added on ends to
make each row 18 characters long.
11
Array Operators
• A.* B
multiplies each element in array A times the corresponding element
in array B
• A./B
divides each element in array A by the corresponding element in
array B
• A.^B
raises each element in array A to the power in the corresponding
element of array B
Addition and Subtraction
• Use + to add two arrays or to add a scalar to an array.
• Use – to subtract one array from another or to subtract
a scalar from an array.
 When using two arrays (vectors or matrices), they
must both have the same dimensions (number of
rows and number of columns).
 Vectors must have the same dimensions (rows and
columns), not just the same number of elements
(1x5 is not the same as 5x1).
13
Addition and Subtraction
When adding two matrices A and B, MATLAB adds the
corresponding elements, i.e.,
• It adds the element in the first row and first column of
A to the element in the first row and column of B.
• It adds the element in the first row and second column
of A to the element in the first row and second column
of B.
• Etc...
This called elementwise addition.
14
Addition and Subtraction
When subtracting two arrays A and
B, MATLAB performs an
elementwise subtraction.
In general, an operation between
two arrays that works on
corresponding elements is called
an elementwise operation.
15
Addition and Subtraction
When adding a scalar to an array,
MATLAB adds the scalar to every
element of the array.
When subtracting a scalar from an
array, MATLAB subtracts the scalar
from every element of the array.
16
Array Multiplication
There are two ways of multiplying matrices – matrix
multiplication and elementwise multiplication.
MATRIX MULTIPLICATION
• The type used in linear algebra.
• MATLAB denotes this with an asterisk (*).
• The number of columns in the left matrix must be
same as number of rows in the right matrix.
17
Matrix Multiplication
18
Matrix Multiplication
19
>> A = randi(3,3)
A =
3
3
1
3
2
2
1
1
3
>> B=randi(3,3)
B =
3
3
1
1
2
2
3
3
3
>> BA = B*A
BA =
19
16
11
9
21
18
>> AB == BA
ans =
0
0
0
0
0
0
12
11
18
1
0
0
>> AB = A*B
AB =
15
18
12
17
19
13
13
14
12
20
Vector Multiplication
When performing matrix multiplication on two vectors:
• They must both be the same size.
• One must be a row vector and the other a column
vector.
• If the row vector is on the left, the product is a scalar.
• If the row vector is on the right, the product is a
square matrix whose side is the same size as the
vectors.
21
Vector Multiplication Examples
>> h = [ 2 4 6 ]
h =
2
4
6
>> v = [ -1 0 1 ]'
v =
-1
>> h * v
ans =
4
>> v * h
ans =
-2
0
2
-4
0
4
-6
0
6
0
1
22
Scalar (Dot) Product
dot(a,b) computes the
inner (scalar) product.
• a and b must be of the same
size.
• Any combination of vertical
or horizontal vectors.
• Result is always a scalar.
EXAMPLE
>> h = [ 2 4 6 ]
h =
2
4
6
>> v = [ -1 0 1 ]'
v =
-1
0
1
>> dot(h,v)
ans =
4
>> dot(v,h)
ans =
4
23
Description
• C = dot(A,B) returns the scalar product of the vectors A and B. A and B
must be vectors of the same length. When A and B are both column
vectors, dot(A,B) is the same as A'*B.
• For multidimensional arrays A and B, dot returns the scalar product along
the first non-singleton dimension of A and B. A and B must have the same
size.
• Examples
• The dot product of two vectors is calculated as shown:
• a = [1 2 3]; b = [4 5 6];
• c = dot(a,b)
• c = 32
24
Cross Product
• cross(a,b) computes the
cross product of two vectors. .
It results in a vector which is
perpendicular to both and
therefore normal to the plane
containing them. It has many
applications in mathematics,
physics, and engineering.
• More info:
EXAMPLE
>> a = [ 1 2 0 ]
a =
1 2 0
>> b = [3 4 0 ]
b =
3 4 0
>> cross(a,b)
ans =
0 0 -2
http://en.wikipedia.org/wik
i/Cross_product
25
Description
•
•
•
•
•
•
•
•
•
•
C = cross(A,B) returns the cross product of the vectors A and B.
That is, C = A x B.
A and B must be 3-element vectors.
Examples
The cross and dot products of two vectors are calculated as shown:
a = [1 2 3]; b = [4 5 6];
c = cross(a,b)
c = -3 6 -3
d = dot(a,b)
d = 32
26
Identity Matrix
A square matrix with ones on main diagonal and zeros
elsewhere.
• When we do a matrix multiplication on any array or
vector with the identity matrix, the array or vector is
unchanged.
 True whether multiply with identity matrix is on the
left or on right
• MATLAB command
eye(n) makes an n×n identity
matrix
27
Determinants
A determinant is a function associated with
square matrices
• In math, determinant of A is written as det(A) or
|A|
• In MATLAB, compute determinant of A with
det(A)
• A matrix has an inverse only if it is square and its
determinant is not zero.
28
Determinants Example
with Cross Product
29
In math, inverse of a matrix A is written as A-1
In MATLAB, get inverse with A^-1 or inv(A)
30
Left division, \:
Left division is one of MATLAB's two kinds of array
division
• Used to solve the matrix equation AX=B
 A is a square matrix, X, B are column vectors
 Solution is X = A-1B
In MATLAB, solve by using left division operator (\),
i.e.,
>> X = A \ B
31
When solving set of linear equations, use
left division, not inverse, i.e., use X=A\B
not X=inv(A)*B
Left division is
• 2-3 times faster
• Often produces smaller error than inv()
• Sometimes inv()can produce erroneous
results
32
Right division, /:
Right division is the other kind of
MATLAB's array division
• Used to solve the matrix equation XC=D
 C is a square matrix, X, D are row vectors
 Solution is X = D·C-1
In MATLAB, solve by using right division
operator (/), i.e.,
>> X = D / C
33
34
Array Division
35
Element by Element Operations
Another way of saying elementwise
operations is element-by-element
operations.
• Addition and subtraction of arrays is always
elementwise.
• Multiplication, division, exponentiation of arrays
can be elementwise.
• Both arrays must be same dimension.
36
Element by Element Operations
Do elementwise multiplication,
division, exponentiation by putting a
period in front of the arithmetic
operator.
37
Element by Element Operations
38
Page 73 of text book!
39
ELEMENTWISE MULTIPLICATION
• Use .* to get elementwise multiplication (notice period
before asterisk)
• Both matrices must have the same dimensions
>> A = [1 2; 3 4];
>> B = [0 1/2; 1 -1/2];
>> C = A .* B
>> C =
0
1
3 -2
40
If matrices not same dimension in elementwise multiplication,
MATLAB gives an error:
>> A = [ 1 2; 3 4];
>> B = [1 0]';
>> A .* B % Meant matrix multiplication!
??? Error using ==> times
Matrix dimensions must agree.
>> A * B % this works
ans =
1
3
41
Element by Element Operations
Be careful – when multiplying square
matrices:
• Both types of multiplication always work.
• If you specify the wrong operator, MATLAB
will do the wrong computation and there
will be no error!
 Difficult to find this kind of mistake.
42
EXAMPLE
>> A = [1 2; 3 4];
>> B = [0 1/2; 1 -1/2];
>> A .* B
>> ans
0
1
3 -2
>> A * B
ans =
2.0000
-0.5000
4.0000
-0.5000
43
Using Arrays in Matlab Built-in Functions
Built-in MATLAB functions can accept arrays as inputs
• When input is array, output is array of same size with each
element being result of function applied to corresponding input
element
 Example: if x is a 7-element row vector, cos(x) is
[cos(x1) cos(x2) cos(x3) cos(x4) cos(x5) cos(x6) cos(x7)]
44
BUILT-IN FUNCTIONS FOR ANALYZING ARRAYS
MATLAB has lots of functions for operating
on arrays. For a vector v
• mean(v) – mean (average)
• max(v) – maximum value, optionally with index
of maximum ([C,I] = max(v))
min(v) – minimum value, optionally with index of
minimum ([C,I] = min(v))
• sum(v) – sum
• sort(v) – elements sorted into ascending order
45
BUILT-IN FUNCTIONS FOR ANALYZING ARRAYS
• median(v) – median
• std(v) – standard deviation
• dot(v,w) – dot (inner product); v, w both vectors
of same size but any dimension
• cross(v,w) – cross product; v, w must both have
three elements but any dimension
• det(A) – determinant of square matrix A
• inv(A) – inverse of square matrix A
• See Table 3-1 in text book for details
on the preceding functions.
46
47