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.

Slides:



Advertisements
Similar presentations
Introduction to MATLAB The language of Technical Computing.
Advertisements

Lecture 4.
3-2 What are relational operators and logical values? How to use the input and disp functions. Learn to use if, if-else and else-if conditional statements.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Chapter 1 Computing Tools Data Representation, Accuracy and Precision Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
General Computer Science for Engineers CISC 106 Lecture 04 Roger Craig Computer and Information Sciences 9/11/2009.
Lecture 4 Sept 8 Complete Chapter 3 exercises Chapter 4.
CIS 101: Computer Programming and Problem Solving Lecture 2 Usman Roshan Department of Computer Science NJIT.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
Concatenation MATLAB lets you construct a new vector by concatenating other vectors: – A = [B C D... X Y Z] where the individual items in the brackets.
Chapter 4 MATLAB Programming Logical Structures Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Loops are MATLAB constructs that permit us to execute a sequence of statements more than once. There are two basic forms of loop constructs: i. while.
EPSII 59:006 Spring Topics Using TextPad If Statements Relational Operators Nested If Statements Else and Elseif Clauses Logical Functions For Loops.
Chapter Seven Advanced Shell Programming. 2 Lesson A Developing a Fully Featured Program.
Chapter 1 Number Sense See page 8 for the vocabulary and key concepts of this chapter.
INTRO TO PROGRAMMING Chapter 2. M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in text files.
Algebra 2: Lesson 5 Using Matrices to Organize Data and Solve Problems.
Creating scalars, vectors, matrices Ex1 & 2. Dot Product & Cross Product Ex3. Plotting Graphs Ex4. Conversion Table Ex5. Plotting functions Finishing Ex4.
Chapter 5. Loops are common in most programming languages Plus side: Are very fast (in other languages) & easy to understand Negative side: Require a.
Array Math.
ARRAY REFERENCING 1 1. II. Array Referencing Assume an array has values. It is useful to “refer to” the elements contained within it – as smaller portions.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Matlab Chapter 2: Array and Matrix Operations. What is a vector? In Matlab, it is a single row (horizontal) or column (vertical) of numbers or characters.
Lecture 2 Using Excel OVERVIEW Complex Formulas Basic Functions Arrays Sorting Data Outlining Data Filtering Data Formatting Tables.
1 Functions 1 Parameter, 1 Return-Value 1. The problem 2. Recall the layout 3. Create the definition 4. "Flow" of data 5. Testing 6. Projects 1 and 2.
Arrays 1 Multiple values per variable. Why arrays? Can you collect one value from the user? How about two? Twenty? Two hundred? How about… I need to collect.
259 Lecture 13 Spring 2013 Advanced Excel Topics – Arrays.
Variables Tutorial 3c variable A variable is any symbol that can be replaced with a number to solve a math problem. An open sentence has at least one.
1 Session 3: Flow Control & Functions iNET Academy Open Source Web Programming.
Array Cs212: DataStructures Lab 2. Array Group of contiguous memory locations Each memory location has same name Each memory location has same type a.
1 Chapter 3 Arrays (2) 1. Array Referencing 2. Common Operations 1. Slicing 2. Diminution 3. Augmentation 3. List of Commonly Used Built-in Functions 1.
Arrays 1 Multiple values per variable. Why arrays? Can you collect one value from the user? How about two? Twenty? Two hundred? How about… I need to collect.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
MATLAB for Engineers 4E, by Holly Moore. © 2014 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. This material is protected by Copyright.
Chapter 4 Review: Manipulating Matrices Introduction to MATLAB 7 Engineering 161.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
File I/O High-Level Functions 1. Definition 2. Is a High-Level function appropriate? 3. xlsread() 4. dlmread() 1.
Logical Ops on Arrays Saving time / avoiding loops 1. Logical Operators 2. Logical Operations 3. Examples: numbers and letters 11.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
ME6104: CAD. Module 4. ME6104: CAD. Module 4. Systems Realization Laboratory Module 4 Matlab ME 6104 – Fundamentals of Computer-Aided Design.
Loops Wrap Up 10/21/13. Topics *Sentinel Loops *Nested Loops *Random Numbers.
ENG College of Engineering Engineering Education Innovation Center 1 Array Accessing and Strings in MATLAB Topics Covered: 1.Array addressing. 2.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Matlab Programming for Engineers
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Digital Image Processing Introduction to M-function Programming.
A (VERY) SHORT INTRODUCTION TO MATLAB J.A. MARR George Mason University School of Physics, Astronomy and Computational Sciences.
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
EGR 115 Introduction to Computing for Engineers MATLAB Basics 1: Variables & Arrays Wednesday 03 Sept 2014 EGR 115 Introduction to Computing for Engineers.
1. Comparing Strings 2. Converting strings/numbers 3. Additional String Functions Strings Built-In Functions 1.
Array Accessing and Strings ENGR 1187 MATLAB 3. Today's Topics  Array Addressing (indexing)  Vector Addressing (indexing)  Matrix Addressing (indexing)
Strings Characters and Sentences 1.Overview 2.Creating Strings 3.Slicing Strings 4.Searching for substrings 1.
To add, subtract, multiply, and divide, absolutely follow the mathematical rules. 1. All the rules 2. The element-per-element operator 3. Ex1: graphing.
Relational and Logical Operators EE 201 1C7-2 Spring 2012.
1-2 What is the Matlab environment? How can you create vectors ? What does the colon : operator do? How does the use of the built-in linspace function.
Chapter 1 Computing Tools Variables, Scalars, and Arrays Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
CS 1023 Intro to Engineering Computing 3: Computer Programming Looping Statements Mark Kerstetter Department of Computer Science Western Michigan University.
Chapter 4 MATLAB Programming
MATLAB: Structures and File I/O
Logical Operations In Matlab.
Loop Statements & Vectorizing Code
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Matlab Basics.
Loop Statements & Vectorizing Code
Presentation transcript:

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 11

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! Note this is UNIQUE to MATLAB. No other software out there does this, so learn your loops and if statements anyway…. 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? 3 2. Which sensors returned negative values? #1 #5# What were the actual negative values?

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 is false, and evaluates to 0 2==4 is false, and evaluates to 0 6>=0 is true, and evaluates to 1 X=4 %X is a scalar 0<=X && mod(X,2)==0 %positive and even is ______, and evaluates to __ 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 6 In this chapter on arrays, only type 1 symbol: &, or |

Logical Operations 1. How many sensors gave negative values? What operation can be done to count the number of negatives? ________ 7 Matlab evaluates the condition on each element. Prints a 1 when true, a zero when false.

Logical Operations, cont. 8 Simply use the built-in function. 1. How many sensors gave negative values?

Logical Operations, cont. 9 negatives is a logical-vector. negatives is also called a ‘mask’. 1. How many sensors gave negative values?

Logical Operations 10 How do we keep going to getting the actual sensor numbers: #1 and #4? 2. Which sensors returned negative values?

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”. 11 whereNegatives is a regular numerical-vector.

Logical Operations What were the actual negative values? What are the actual values located at positions 1 and 4?

Logical Operations 13 3 methods possible: 1. Use the logical vector negatives of 0’s and 1’s. 2. Use the numerical vector whereNegatives of indices. sensor is the vector that has the values. It makes sense it comes first, since we are accessing those values.

Logical Operations 14 3 methods possible: 3. Use the condition (bypass previous variables) All these are logical operations. Logic (true/false) is used to find values.

Quick Summary To get a logical vector: (0’s and 1’s) result1 = x>=0; %var =condition; result = To get the actual positions: result2 = find(x>=0); %var =find(condition); result = To get the actual values: result = x(result1) ; %use the logical vector result = x(result2) ; %use the actual positions result = x(x>=0) ; %use the condition result = Let’s see examples…

Ex1 – Filtering Data Wind tunnels are commonly used to measure pressure changes, velocities changes, etc… Some use powerful electronic sensors, some use HD cameras and dyes in the air, others (like ERAU lab) use manometer tubes AIR FLOW Static Fluid Equation: ΔP = ρgh ±h

Ex1 – Filtering the tubes % assume a vector of manometer reading % h difference in millimeters: -500<values<500 ManoReadings = rand(1,20)* ; % 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 % calculate difference in pressure at each point… 17

Ex1 - Output 18 Logical operation: find() Logical operation: variableName(positions)

Ex1 – Complete the software… % assume a vector of manometer reading % h difference in millimeters: -500<values<500 ManoReadings = rand(1,20)* ; % 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 % calculate difference in pressure at each point… 19 Replace by readings from machine!

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)); 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)); 20 Use only 1 symbol for AND and OR.

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)); 21 Use only 1 symbol for AND and OR.

Ex3 – How about matrices? 22 Part NumberUnit Price ($) The client orders 100 pieces of part number 65. How much is his total bill, with a tax of 6.5%?  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 [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) 23 >> [row, col] = find(table == part_number) row = 2 col = 1

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! %find the row of that part number, column1 ONLY row = find(table == part_number); 24 >> [row, col] = find(table == part_number) row = 2 3 col = 1 2 Part NumberUnit Price ($) That’s SLICING again! (:,1)

Ex4 – Works for strings too! 25 Simulate DNA with a string GATACCAT… The problem is: Generate the matching DNA string! A-T T-A C-G G-C Source:

Ex4 – Works for strings too! 26 Using a loop, and an if statement originalDNA =‘GATACCAT’; matchDNA = []; %empty container for the matching DNA %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 length() is used to count the number of elements in a vector, here: number of characters

Ex4 – Works for strings too! 27 originalDNA = GATACCAT matchDNA = A A matchDNA = TAT TA matchDNA = CTAT TA matchDNA = CTATGGTA Or.. In 5 lines! originalDNA =‘GATACCAT’ %at the T's location, put an ‘A’ matchDNA(originalDNA =='T')='A' %at the A’s location, put a T matchDNA(originalDNA =='A')='T‘ %at the G’s location, put a C matchDNA(originalDNA =='G')='C‘ %at the C’s location, put a G matchDNA(originalDNA =='C')='G'

One last keyword end It represents automatically the index of the last element in a vector 28

Wrapping Up The OR and AND operators are slightly updated to 1 symbol 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) 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!) 29