10_lecture_20100216_Arrays3

Download Report

Transcript 10_lecture_20100216_Arrays3

Chapter 3
Arrays (3)
1.
Arithmetic Operations
Add/subtract
Multiply/divide
1.
2.
1.
2.
Solving a System of Equations
Logical Operations
1.
2.
3.
Logical Operators
Logical Operations
Examples
1
A.
B.
Add/Subtract
Multiply/Divide
ARITHMETIC OPERATIONS
2
1. Add & Subtract

Overall, you can add and subtract any variable that
has the same dimension.

Scalars:
Result = 2 + 3 – 9 – 2*x ; %assumes x is a scalar

Vectors
Assume v1, v2, v3 all have 1 row, 3 columns
Results = v1 –v2 + v3;

Matrices
Assume m1, m2, and m3 all have 2 rows, 3 columns
Results = m1 + m2 – m3;


However, there is one obvious exception..
3
Using Scalars

Adding and subtracting a single scalar to each element of an
array is straightforward and obviously does not require the
dimensions to match:
Original Array:
>> A+2
ans =
8
11
6
Addition
>> A=[6 9 4; 3 -5 2]'
A =
6
3
9
-5
4
2
5
-3
4
>> A-5
ans =
1
4
-1
-2
-10
-3
Subtraction
4
Using Vectors
17
?
3
9
10
?
Advantage of arrays? 3
variables instead of 6 (one
for each value)
5
Source: hyperphysics.phy-astr.gsu.edu/hbase/vect.html
Using Vectors

There is no limit to the amount/directions of vectors.

The dimensions of each vector must match: here [x, y]
6
Source: hyperphysics.phy-astr.gsu.edu/hbase/vect.html
Q&A

State whether each command works or not:
A= [-37.0
4
B = [23
3];
R = A + B
3.3];
A= [-4 56 4];
B = [23
7
3];
R = A - B
YES or NO?
A= [-37.0
4
B = [23; 6.1;
R = A + B
3.3];
3];
YES or NO?
YES or NO?
A= [-37.0
4
B = [23; 6.1;
R = A + B
3.3];
3]’;
YES or NO?
7
Using Matrices

You can add two matrices of the same size by adding
individual elements located at the same position
(row,col).
6 3
9 -5
4 2
A
1 3
2 2
4 7
6+1
9+1
4+4
3+3
-5+2
2+7
B
7
6
11 -3
8
9
Result
8
Using Matrices

You can subtract two matrices of the same size by
subtracting individual elements located at the same
position (row,col).
6 3
9 -5
4 2
1 3
2 2
4 7
6-1
9-2
4-4
3-3
-5-2
2-7
A-B
1 3
2 2
4 7
5 0
7 -7
0 -5
Result1
6 3
9 -5
4 2
1-6
2-9
4-4
3-3
2--5
7-2
B-A
-5 0
-7 7
0
5
Result2
A-B is not equal to B-A!
9
2. Multiplication & Division

You can multiple and divide arrays together, not as
long as the dimensions match, but rather as long as
the MATHEMATICAL EXPRESSION is valid.

Caution must be taken even with scalars!

Special element-per-element operators (symbols) must be
used to bypass the default matrix operations.
10
Source: hyperphysics.phy-astr.gsu.edu/hbase/vect.html
Using Scalars with Vectors and
Matrices

Multiplying, and dividing each element of an array by a
single scalar is almost straightforward:
>> A=[6 9 4; 3 -5 2]'
A =
6
3
9
-5
4
2
Original Array
>> A/2
ans =
3.0000
4.5000
2.0000
Division
1.5000
-2.5000
1.0000
>> A*1.1 %or 1.1*A
ans =
6.6000
3.3000
9.9000
-5.5000
4.4000
2.2000
Multiplication
• What if you wanted to have (2/each
element) of the array, like:
[ 2/6 2/9 2/4; 2/3 2/-5 2/2]’?
Would 2/A work: YES or NO?
11
Using Scalars with Vectors and
Matrices

Multiplying, and dividing each element of an array by a
single scalar is almost straightforward:
>> A=[6 9 4; 3 -5 2]'
A =
6
3
9
-5
4
2
Original Array

To divide by a matrix in Matlab mathematically means “to
multiply by the inverse of the matrix”. As written, it is the
“matrix division of A into 2”, but to do this, the
dimensions of A and 2 have to match (which is not the case!)
12
Element-per-element operator

To bypass the matrix-operation, use the element-perelement operator >> . << (pronounced the “dot-operator”).
A =
2/6
2/9
2/4
The DOT operator!
2/3
2/-5
2/2
The dot goes BEFORE the / operator!
13
Vector multiplication

To calculate the product of two vectors, using the regular
star >> * << operator




one must be a row vector
the other one must be a column vector
both must contain the same number of elements
But what exactly does it do? …
A * B = ?
A =
B * A = ?
6
9
4
(3 by 1)
B =
1
2
-1
? = 6
18
-4
(1 by 3)
? = 6
18
-4
14
Vector multiplication

Matrix multiplication …
A =
6
9
4
B =
1
2
-1
(1 by 3)
(3 by 1)
A * B = ?
15
Vector multiplication

B =
1
Matrix multiplication …
A =
2
(1 by 3)
-1
6
9
4
(3 by 1)
B * A = ?
This is equivalent to dot(A,B) , and dot(B,A)!!
1*6 + 2*9 + (-1)*4 = 6+18-4 = 20
16
Real Life #1. Dot product and
cross product

Remember the DOT product? (maybe/maybe not)
Credits to:
http://www.itee.uq.edu.au/~c
ogs2010/cmc/chapters/Hebbi
an/ten5.gif
The DOT product…

In Matlab
a = [1; 0.6; -2]; <enter>
b = [-1 ; 0; 0.2]; <enter>
result = dot(a,b) <enter>
17
Vector multiplication

How do we get this?
A =
6
9
4
B =
1
2
-1
(1 by 3)
(3 by 1)
? = 6
18
-4
(3 by 1)
• Again:
Use the dot-operator to evaluate element-per-element. In this case, the
dimensions MUST match: rows AND columns (hence the apostrophe)!
18
Vector multiplication

How about the other direction?
A =
6
9
4
B =
1
2
-1
(1 by 3)
(3 by 1)
? = 6
18
-4
(1 by 3)
19
Q&A - multiplication

State whether each command works or not:
A= [-37.0
4
B = [23
3];
R = A * B
3.3];
A= [-4 56 4];
B = [23
7
3];
R = A *. B
YES or NO?
A= [-37.0
4
B = [23; 6.1;
R = B * A
3.3];
3];
YES or NO?
A= [-37.0
R = A * A
4
3.3];
YES or NO?
YES or NO?
20
Real life #1 - Plotting graphs

In this case:
x = linspace(-10,10,20); %array of 20 data points
y = x.^2;
%calculate array of y’s.
%(The dot will be explained next time…)
plot(x,y)
%plot command
Using:
y = x*x would not work
y = x^2 neither
Matlab would try to do vector
multiplication!
21
Real life #2 – Calculating
22
Matrix multiplication

To multiply matrices using the * operator, the
inner-dimensions must match.

What this means:
..
.. ..
..
..
..
..
..
R1 by C1
*
.. ..
..
..
..
..
..
R2 by C2
C1 must be
equal to R2
.. ..
..
..
..
..
R1 by C2
Ironically, the resulting matrix has
R1 rows and C2 columns!
23
Matrix multiplication
6 3
9 -5
4 2
3 by 2
*
1 3
2 2
6*1+3*2
6*3+3*3
9*1-5*2
9*3-5*2
4*1+2*2
4*3+2*2
2 by 2
3 by 2
Don’t be scared: it’s just math…
You’ll learn it eventually.
What you need to understand is that the * operator is NOT meant
to multiply element by element
24
Matrix multiplication/division
M
U
L
T
I
P
L
Y
Same dimensions: 3 by 2
>> a.*b
6 3
9 -5
4 2
.*
1 3
2 2
4 -1
6*1
3*3
9*2
-5*2
4*4
2*-1
Element per element
ans =
6
18
16
3 by 2
9
-10
-2
Same dimensions: 2 by 2
D
I
V
I
D
E
>> c./d
6 3
9 -5
./
1 3
2 2
6/1
3/3
9/2
-5/2
ans =
6.0000
4.5000
1.0000
-2.5000
2 by 2
Element per element
25
Left-Division

There is an unusual operator that can be
applied to matrices:


The back-slash:
\
The example that follows shows one
application of this “left-divide” operator.
26
Real life #2. Solving a system of 2
equations

Suppose the following system of equations:
X + Y = 11
2*X – Y = 9
Solve for {X,Y} that satisfies both equations
simultaneously!
Which methods have you used? _______________
27
Manual Method

Solving using substitution:
X + Y = 11
2*X – Y = 19
First:
Second:
Third:
Fourth:
Use first equation to solve for Y
Y = 11 –X
Plug that Y back in second equation
2*X – (11-X) = 19
Now, rearrange
3*X – 11 = 19
and solve for X
X = (19+11)/3 = 30/3=10
Plug X back into first step to solve for Y
Y = 11 – X = 11 – 10 = 1
X=10
Y =1
28
Matlab Method – Matrices (1/2)

Recall the original system
X + Y = 11
2*X – Y = 19

Take each X and Y coefficient to create a matrix
1*X + 1*Y = 11
2*X – 1*Y = 19
A=

1
1
2
-1
Take the right side values and create a column-vector
1*X + 1*Y = 11
2*X – 1*Y = 19
b=
11
19
29
Matlab Method – Matrices (2/2)

Left-divide A by b!

Tadaaaa….
Use the \ operator (NOT the regular division symbol)
Matlab solves for each unknown, in
the order it was placed in matrix A.
In our case, X was first, Y came
second!
30
Real life #4. Solving a system of 3
equations (1/2)

Suppose the following system of equations:
x – 3y + 3z = -4
2x + 3y –z = 15
4x – 3y –z =19
Solve for {X,Y,Z} that satisfies both equations
simultaneously! What would be A and b?
A=
?.
?.
?.
2.
?
3
?.
-1
? ..
4.
-3 . -1 .
?.
b=
15
?
.
.
19
31
The answer to the system:
x=5
y=1
Much faster
than
manually
solving
this!!!
z = -2
32
A.
B.
General Idea
Examples-examples-examples
LOGICAL OPERATIONS
33
General Idea

Applied to arrays, this solves problems such as…
Find where the positives are positioned
 Count the number of negatives
 Delete the negatives
 Sum all the evens
 Replace all the negatives by zero
… These can easily be solved in 1 or 2 lines, without the use of any
loop and if statement.


This is very useful in engineering, as tables of data
always have to be filtered before use!

Note this is UNIQUE to MATLAB. No other software out there does this, so
learn your loops and if statements anyway….
34
General Idea

Recall all the logical operators (> >= < <= ~= == && ||)

Logical Operations return a:


1 when the condition is evaluated to be true
0 when the condition is evaluated to be false
2>5
2==4
6>=0
In this chapter on
arrays, you must
only type 1 symbol:
&, or |
is false, and evaluates to 0
is false, and evaluates to 0
is true, and evaluates to 1
X=4
0<=X && mod(X,2)==0 %positive and even
is ______, and evaluates to __
35
Logical Operations
…
Matlab evaluates the condition on each element.
Prints a 1 when true, a zero when false.
How would you use this result to count the number
of negative numbers that were randomly generated?
________________________________________
36
Vector Operations
Logical Vectors – an array of 0’s and 1’s indicating
which elements meet a criteria:
e.g.
Values = floor(rand(1, 5)*25);
X = mod(Values, 2)==0 % which elements are even?
X =
0
1
0
1
1
Used for creating a “mask” – using logical & and |, X
can be used to select elements of vectors
37
Vector Operations, cont.
Real-Life: Masks for raster graphics
http://en.wikipedia.org/wiki/Mask_(computing)
38
Ex1 – Find the actual positions of
the positives

Matlab offers a built-in function named find().

Applied to a vector, it finds where the condition is true,
and returns an array of the actual positions, NOT the
zeros and ones.
39
Vector Operations, cont.
Logical Indexing: like find()- returns a vector of
values meeting a logical criteria
Values = floor(rand(1, 5)*25);
Z = Values(mod(Values, 2)==0)
Z =
18
18
16
4
40
Ex2 – Delete all the numbers less
than 32
%Suppose a vector x of values
%find the POSITIONS of the numbers < 32
positions = find(x<32);
%in x, delete the numbers at these positions
x(positions) = []; %delete!
OR
%Suppose a vector x of values
%evaluate where numbers<32 is true
whereTrue = x<32;
%delete when true
x(whereTrue) = []; %delete!
41
Ex3 – Sum all the positive evens
%Suppose a vector x of whole values
%find the POSITIONS of the positive even numbers
positions = find(mod(x,2)==0 & x>=0);
%in x, sum the numbers at these positions
result = sum(x(positions));
Use only 1 symbol for
AND and OR.
OR
%Suppose a vector x of whole values
%evaluate where “numbers is even” is true
whereTrue = (mod(x,2)==0 & x>=0);
%delete when true
result = sum(x(whereTrue));
42
Ex4 – Sum all the evens
%Suppose a vector x of whole values
%find the POSITIONS of the even numbers
positions = find(mod(x,2)==0);
%in x, sum the numbers at these positions
result = sum(x(positions));
OR
%Suppose a vector x of whole values
%evaluate where “numbers is even” is true
whereTrue = (mod(x,2)==0);
%delete when true
result = sum(x(whereTrue));
43
Ex5 – how about matrices?
Part Number
Unit
Price ($)
101
3.25
65
20.50
290
56.00
450
1.75
The client orders 100 pieces of part number 65. How much is his total bill, with a
tax of 6.5%?
44
 The part number and quantity can change, hard-coding is not an option!
Ex5 – Analyze table, cont.
%ask user for part number, and quantity
part_number = input(‘Enter part number: ’);
quantity = input(‘How many did u buy? ’);
%find the row of that part number
[row, col] = find(table == part_number);
>> [row,
col] = find(table == part_number)
%in table, get the actual unit
price
unit_price = table(row,2); row =
2
col =
1
%calculate sub-total
sub_total = quantity*unit_price;
%add in taxes
total_bill = sub_total * (1+0.65);
fprintf(‘Your bill adds up to: $%20.2f\n’, total_bill)
45
Ex5 – Analyze table, cont.

Note that this wouldn’t go well if the part_number’s value
is actually also a unit price!
Part Number
Unit
Price ($)
101
3.25
65
20.50
290
65.00
450
1.75
>> [row, col] = find(table == part_number)
row =
2
3
col =
1
2
%find the row of that part number, column1 ONLY
row = find(table(:,1) == part_number);
That’s SLICING again!
46
Ex6 – Works for strings too!



Simulate DNA with a string
GATACCAT…
The problem is: Generate the
matching DNA string!




A-T
T-A
C-G
G-C
47
Ex5 – Works for strings too!

Using a loop, and an if statement
originalDNA =‘GATACCAT’;
matchDNA = []; %empty container for the matching DNA
length() is used to count the number of elements
in a vector, here: number of characters
%loop for each letter
for ctr = 1:length(originalDNA)
if originalDNA(ctr) == ‘T’ %Where it is a ‘T’, make the ‘A’
matchDNA(ctr)=‘A’;
elseif originalDNA(ctr) == ‘A’
matchDNA(ctr)=‘T’;
elseif originalDNA(ctr) == ‘C’
matchDNA(ctr)=‘G’;
elseif originalDNA(ctr) == ‘G’
matchDNA(ctr)=‘C’;
end
end
48
Ex5 – Works for strings too!

Or.. In 5 lines!
originalDNA =
GATACCAT
originalDNA =‘GATACCAT’
%find where T's are
matchDNA(originalDNA =='T')='A'
matchDNA =
A
A
%find where A's are
matchDNA(originalDNA =='A')='T‘
matchDNA =
TAT TA
%find where G's are
matchDNA(originalDNA =='G')='C‘
matchDNA =
CTAT TA
%find where C's are
matchDNA(originalDNA =='C')='G'
matchDNA =
CTATGGTA
49
One last keyword

end

It represents automatically the index of the last element in a vector
50