Logical Operations on Arrays
Download
Report
Transcript Logical Operations on Arrays
Logical Ops’ on Arrays
When we need to compare
arrays, find a number within an
array, isolate all invalid
numbers…
1.Logical
Operators
2.Logical Operations
3.4 Examples: numbers and letters
1
General Idea
Applied to arrays, this solves problems such as…
Find where the positives are positioned
Count the number of negatives
Delete the negatives, or maybe replace them by zeros
Replace letters by other letters
In Matlab, these can easily be solved in 1 or 2 lines, without the use
of any loop and if statement (necessary in Java, C, C++..)
This is very useful in engineering, as tables of data
always have to be filtered before use!
2
General Idea
Suppose an array of values (vector or matrix) exists. The
values came from sensors on a rocket, on a robot, on a
car, etc...
How many sensors gave negative values?
1.
3
Which sensors returned negative values?
2.
#1
#5
#288
What were the actual negative values?
3.
-2003.2
-100.2
-552.45
3
General Idea
Suppose a document with letters, words and sentences.
(An array of letters).
1.
How many capital letters are there?
2.
Extract the capital letters, keep them in order.
3.
At what positions are the capital letters located?
4.
Encrypt the document by changing all a’s to z’s?
4
General Idea
Recall the relational and 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
is false, and evaluates to 0
is false, and evaluates to 0
is true, and evaluates to 1
5
General Idea
Recall the relational and logical operators
(> >= < <= ~= == && ||)
Logical Operations return a:
1 when the condition is evaluated to be true
0 when the condition is evaluated to be false
X= [ ... ]; %X is a not a scalar
0<=X & mod(X,2)==0 %positive and even
In this chapter on
arrays, only type 1
symbol: &, or |
6
Logical Operations
1.
How many sensors gave negative values?
Matlab evaluates the condition on
each element.
Prints a 1 when true, a zero when false.
What operation can be done to count the number of
negatives? ________
7
Logical Operations, cont.
1.
How many sensors gave negative values?
Simply use the built-in function.
8
Logical Operations, cont.
1.
How many sensors gave negative values?
negatives is a logical-vector.
negatives is also called a ‘mask’.
9
Logical Operations
2.
Which sensors returned negative values?
How do we keep going to getting the
actual sensor numbers: #1 and #4?
10
Logical Operations, cont.
Matlab offers a built-in function that finds the index of
values that make a condition true. In other word here,
“find where the sensor-values are negatives”.
whereNegatives is a regular numerical-vector.
11
Logical Operations
What were the actual negative values?
3.
What are the actual values located at positions 1 and 4?
12
Logical Operations
3 methods possible:
1.
Use the logical vector negatives of 0’s and 1’s.
sensor is the vector that
has the values. It makes
sense it comes first,
since we are accessing
those values.
13
Logical Operations
3 methods possible:
1.
Use the logical vector negatives of 0’s and 1’s.
2.
Use the numerical vector whereNegatives of indices.
14
Logical Operations
3 methods possible:
3.
Use the condition (bypass previous variables)
All these are logical operations. Logic (true/false) is used
to find values.
15
Quick Summary
To get a logical vector: (0’s and 1’s)
result1= (x>=0);
result =
0
1
0
1
0
%var=condition;
0
0
1
To get the actual positions:
result2= find(x>=0);
result =
2
4
%var=find(condition);
8
To get the actual values:
result= x(result1); %use the logical vector
result= x(result2); %use the positions
result= x(x>=0);
%use the condition
result =
34.2
55.5
9.9
16
Let’s see examples…
Ex1 – Filtering Data
www.trucktrend.com
Wind tunnels are commonly used to
measure pressure changes, velocity
changes, etc… Some use powerful
electronic sensors, some use HD cameras
and dyes in the air, others (like ERAU lab)
use manometer tubes.
www.allamericanracers.com
AIR
FLOW
http://ceit.uq.edu.au
±h
Static Fluid Equation: ΔP = ρgh
17
Ex1 – Filtering the tubes
% assume a vector of manometer reading
% h difference in millimeters: -500<values<500
% indicate which tubes may not have not-worked, and
% should be looked at (+/- 50 millimeter change)
%if at least 1 was bad
%display which tubes, and what were the readings
18
Ex1 – Filtering the tubes
% assume a vector of manometer reading
% h difference in millimeters: -500<values<500
ManoReadings = rand(1,20)*1000-500;
% indicate which tubes may not have not-worked, and
% should be looked at (+/- 50 millimeter change)
shouldBeFixed = find(-50<=ManoReadings & ManoReadings<=50);
if length(shouldBeFixed) ~=0 %if at least 1 was bad
disp('These tube numbers did not change much:')
disp(shouldBeFixed)
disp('Their values were:')
disp(ManoReadings(shouldBeFixed))
end
19
Ex1 - Output
Logical operation: find()
Logical operation:
variableName(positions)
20
Ex1 – Complete the software…
% assume a vector of manometer reading
% h difference in millimeters: -500<values<500
ManoReadings = rand(1,20)*1000-500; Replace by readings from machine!
% indicate which tubes may not have not-worked, and
% should be looked at (+/- 50 millimeter change)
shouldBeFixed = find(-50<=ManoReadings & ManoReadings<=50);
if length(shouldBeFixed) ~=0 %if at least 1 was bad
disp('These tube numbers did not change much:')
disp(shouldBeFixed)
disp('Their values were:')
disp(ManoReadings(shouldBeFixed))
end
21
Ex2 – Sum all the positive evens
%Suppose a vector x of whole values
%evaluate where “numbers is even” is true
%sum when true
22
Ex2 – Sum all the positive evens
%Suppose a vector x of whole values
%evaluate where “numbers is even” is true
whereTrue = (mod(x,2)==0 & x>=0);
% sum when true
result = sum(x(whereTrue));
Use only 1 symbol for
AND and OR.
OR
%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));
23
Ex2 – Sum all the positive evens
OR
%Suppose a vector x of whole values
%sum the positive, even numbers of x
result = sum(x(mod(x,2)==0 & x>=0));
Use only 1 symbol for
AND and OR.
24
Ex3 – 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%?
25
The part number and quantity can change, hard-coding is not an option!
Ex3 – Analyze table, cont.
%ask user for part number, and quantity
part_number = input(‘Enter part number: ’);
quantity = input(‘Enter quantity: ’);
%find the row of that part number
%in table, get the actual unit price
%calculate sub-total
%add in taxes
.
26
Ex3 – Analyze table, cont.
%ask user for part number, and quantity
part_number = input(‘Enter part number: ’);
quantity = input(‘Enter quantity: ’);
%find the row of that part number
[row, col] = find(table == part_number);
%in table, get the actual unit price
unit_price = table(row,2);
%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)
27
Ex3 – Analyze table, cont.
Note that this would not go well if the part_number’s
value is actually also one of the 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!
28
Ex4 – Works for strings too!
Simulate DNA with a string
GATACCAT…
The problem is: Generate the
matching DNA string!
Source: http://www.scq.ubc.ca
A-T
T-A
C-G
G-C
29
Ex4 – 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
30
Ex4 – Works for strings too!
Or.. In 5 lines!
originalDNA =
GATACCAT
originalDNA =‘GATACCAT’
%at the T's location, put an ‘A’
matchDNA(originalDNA =='T')='A'
matchDNA =
A
A
%at the A’s location, put a T
matchDNA(originalDNA =='A')='T‘
matchDNA =
TAT TA
%at the G’s location, put a C
matchDNA(originalDNA =='G')='C‘
matchDNA =
CTAT TA
%at the C’s location, put a G
matchDNA(originalDNA =='C')='G'
matchDNA =
CTATGGTA
31
fprintf( ) and arrays
Assume you have a vector of temperatures
Temperature=[100, 100.2, 99, 89, 110]
Temperature =
100.0000 100.2000 99.0000 89.0000 110.0000
fprintf('Temperature is %.2fF\n',Temperature)
Temperature is 100.00F
Temperature is 100.20F
Temperature is 99.00F
Temperature is 89.00F
Temperature is 110.00F
32
fprintf( ) and arrays
Recall the parts and price table:
fprintf('partnumber %d, price $%.2f\n', table')
partnumber 101, price $3.25
partnumber 65, price $20.50
partnumber 290, price $56.00
partnumber 450, price $1.75
33
Wrapping Up
The OR and AND operators are slightly updated
What does it mean: To “evaluate”
True evaluates to 1
False evaluates to 0
Logical vectors are vectors of 0’s and 1’s.
find(condition) returns a numerical vector of positions where
the condition is true.
3 methods to access (to refer to) the actual elements
It works with letters too. (encryption)
When using fprintf( ), one placeholder can print the whole array
The keyword end (nothing to do with the if/switch/for/while) refers to
the last element in the array. (note it will be black, not blue!)
34