Engr/Math/Physics 25 Chp4 MATLAB Programming-2 Bruce Mayer, PE Licensed Electrical & Mechanical Engineer BMayer@ChabotCollege.edu Engineering/Math/Physics 25: Computational Methods 1 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Learning Goals Write MATLAB Programs That can MAKE “Logical” Decisions that Affect Program Output Write Programs that Employ LOOPing Processes • For → No. Loops know a priori • while → Loop Terminates based on Logic Criteria Engineering/Math/Physics 25: Computational Methods 2 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Large Program Development - 1 1. Writing and testing of individual modules (the unit-testing phase). 2. Writing of the top-level program that uses the modules (the build phase). • • Not all modules are included in the initial testing. As the build proceeds, more modules are added. Develop Software as a Series of Incremental Builds; i.e., Build-a-Little, Test-a-Little, Repeat Engineering/Math/Physics 25: Computational Methods 3 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Large Program Development - 2 3. Testing of the first complete program (the alpha release phase). • This is usually done only in-house by technical people closely involved with the program development. There might be several alpha releases as bugs are discovered and removed. 4. Testing of the final alpha release by in-house personnel and by familiar and trusted outside users, who often must sign a confidentiality agreement. This is the beta release phase, and there might be several beta releases. Engineering/Math/Physics 25: Computational Methods 4 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Finding Programming Errors Errors in Software Code are Called “Bugs” • Contrary to the Popular Notion, using the term "bug" to describe inexplicable defects or flaws did NOT originate with Computers – “Bug” had been Used for Decades-Prior to describe Mechanical Malfunctions; Consider this Letter from Thomas Edison to a Associate in 1878 It has been just so in all of my inventions. The first step is an intuition, and comes with a burst, then difficulties arise—this thing gives out and [it is] then that “Bugs” - as such little faults and difficulties are called - show themselves and months of intense watching, study and labor are requisite before commercial success or failure is certainly reached. Engineering/Math/Physics 25: Computational Methods 5 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt 1st Computer Bug – Circa 1945 attributed to Grace Hopper, who publicized the cause of a malfunction in an early electromechanical computer Engineering/Math/Physics 25: Computational Methods 6 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Finding Errors (DeBugging) Debugging a program is the process of finding and removing the “bugs,” or errors, in a software program. Program errors usually fall into one of the following categories. 1. Syntax errors such as omitting a parenthesis or comma, or spelling a command name incorrectly. • MATLAB usually detects the more obvious errors and displays a message describing the error and its location. Engineering/Math/Physics 25: Computational Methods 7 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Types of Bugs cont 2. Errors due to an incorrect mathematical procedure. • • Called RUNtime errors. They do not necessarily occur every time the program is executed; their occurrence often depends on the particular input data. – A common example is Division by Zero – Another example is the production of COMPLEX results when not expected Engineering/Math/Physics 25: Computational Methods 8 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Locating RUNtime Errors 1. Always test your program with a simple version of the problem, whose answers can be checked by hand calculations. 2. Display any intermediate calculations by removing semicolons at the end of statements 3. ADD & Display TEMPORARY Intermediate results • Can Comment Out later if Desired Engineering/Math/Physics 25: Computational Methods 9 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Locating RUNtime Errors cont. 4. To test user-defined functions, try commenting out the function line and running the file as a script. 5. Use the debugging features of the Editor/Debugger, as Discussed in §4.8 of the TextBook Engineering/Math/Physics 25: Computational Methods 10 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt ReCall RELATIONAL Operators Symbol < <= > >= == ~= Meaning Less than Less than or equal to Greater than Greater than or equal to Equal to Not equal to Expressions Evaluated With Relational Operators Produce a Quantitative Result in BINARY form; either “1” or “0” Engineering/Math/Physics 25: Computational Methods 11 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Relational Operator Examples Given x = [6,3,9] and y = [14,2,9] • A MATLAB Session >> z = (x < y) z = 1 0 0 >> z = (x ~= y) z = 1 1 0 >> z = (x > 8) z = 0 0 1 Engineering/Math/Physics 25: Computational Methods 12 relational operators can be used for array addressing • With x & y as before >> z = x(x<y) z = 6 • finds all the elements in x that are less than the corresponding elements in y – e.g. x(1) = 6 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Operator Precedence The arithmetic operators +, -, *, /, and \ have precedence over the relational operators Thus the statement z = 5 > 2 + 7 • Is Equivalent to z = 5 >(2+7) • Returns Result z = 0 Engineering/Math/Physics 25: Computational Methods 13 Parentheses Can Change the Order of Precedence; for example >> z = 5 > 2 + 7 z = 0 >> z = (5 > 2) + 7 z = 8 >> z = (5>2) z = 1 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt The Logical Class When the RELATIONAL operators are used, such as x = (5 > 2) they CREATE a LOGICAL variable, in this case, x Logical variables may take only two values: • 1 (true) • 0 (false) Engineering/Math/Physics 25: Computational Methods 14 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt The Logical Class cont Just because an array contains only 0s & 1s, however, it is not necessarily a logical array. • For example, in the following session k and w appear the same, but k is a logical array and w is a numeric array, and thus an error message is issued >> x = [-2:2]; k = (abs(x)>1) k = 1 0 0 0 1 >> z = x(k) z = -2 2 >> w = [1,0,0,0,1]; v = x(w) ??? Subscript indices must either be real positive integers or logicals. Engineering/Math/Physics 25: Computational Methods 15 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Accessing Arrays w/ Logicals When a logical array is used to ADDRESS another array, it extracts from that array the ELEMENTS in the locations where the logical array has 1s. Engineering/Math/Physics 25: Computational Methods 16 So typing A(B), where B is a logical array of the same size as A, returns the VALUES of A at the indices (locations) where B is 1. Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Accessing Arrays w/ Logicals cont Specifying array subscripts with logical arrays extracts the elements that correspond to the true (1) elements in the logical array Given 3x3 array: • A = [5,6,7; 8,9,10; 11,12,13] • and Engineering/Math/Physics 25: Computational Methods 17 >> B = logical(eye(3)) B = 1 0 0 1 0 0 0 0 1 Extract the diagonal elements of A >> C = A(B) C = 5 9 13 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Logical Operators for Arrays Definition Oper. Name ~ NOT & AND | OR ~A returns an array the same dimension as A; the new array has ones where A is zero and zeros where A is nonzero A & B returns an array the same dimension as A and B; the new array has ones where both A and B have nonzero elements and zeros where either A or B is zero A | B returns an array the same dimension as A and B; the new array has ones where at least one element in A or B is nonzero and zeros where A and B are both zero. Engineering/Math/Physics 25: Computational Methods 18 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Boolean Logic The Logical Operators Form The Basis of BOOLEAN (Two Value, T & F, 1 & 0, or Hi & Lo) Logic • Developed by George Boole (1815-1864) The Action of the Boolean Operators are Often Characterized with TRUTH Tables AND (all high = high, else low) NOT (inverter) Input 1 Input 2 Output Input 1 Input 2 Output Input = 1 Output = 0 0 0 0 0 0 0 Input = 0 Output = 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 1 1 1 1 Engineering/Math/Physics 25: Computational Methods 19 OR (any high = high, else low) Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Venn Diagrams for Booleans AND Operator • ALL Terms are Present • ANY ONE of the terms are present • AND represents the INTERSECTION (∩) of Sets • OR represents the UNION (U) of Sets Engineering/Math/Physics 25: Computational Methods 20 OR Operator Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Xor → EXCLUSIVE or MATLAB SynTax C = xor(A, B) xor Evaluates as TRUE Only If EACTLY ONE of A or B is True, but NOT BOTH • Xor Venn Diagram Engineering/Math/Physics 25: Computational Methods 21 Xor Truth Table XOR (different = high, same = low) Input 1 Input 2 Output 0 0 0 0 1 1 1 0 1 1 1 0 “Logic Gate” Symbol used in Electrical Engineering Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Other Logic Gates NOR ~| NAND ~& • “Not OR” • “Not AND” NAND (all high = low, else high) NOR (any high = low, else high) Input 1 Input 2 Output Input 1 Input 2 Output 0 0 1 0 0 1 0 1 1 0 1 0 1 0 1 1 0 0 1 1 0 1 1 0 NANDs & NORs are easier to implement in HARDWARE than are ANDs & ORs • i.e., They take Fewer Transistors Engineering/Math/Physics 25: Computational Methods 22 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Boolean Algebra Boolean Logic can be Mathematically Formalized with the use of Math Operators The Math Operators Corresponding to Boolean Logic Operations: Operator Usage Notation AND A AND B A.B or A·B OR NOT A OR B NOT A A+B ~A or A • A and B can only be TRUE or FALSE • TRUE represented by 1; FALSE by 0 Engineering/Math/Physics 25: Computational Methods 23 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Boolean Algebraic Properties Commutative: A.B = B.A and A+B = B+A Distributive: • A.(B+C) = (A.B) + (A.C) • A+(B.C) = (A+B).(A+C) Identity Elements: 1.A = A and 0 + A = A Inverse: A.A = 0 and A + A = 1 Associative: • A.(B.C) = (A.B).C and A+(B+C) = (A+B)+C DeMorgan's Laws: • A.B = A + B and • A+B = A.B Engineering/Math/Physics 25: Computational Methods 24 Verify DeMorgan in MATLAB Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt DeMorgan in MATLAB Work Problem 14 → Case-a: A B A B ? >> % case-a >> x = 7 x = 1 1 7 >> a1 = ~((x < 10)&(x >= 6)) a1 = 0 0 0 >> a2 = (~(x < 10))|(~(x >= 6)) a2 = 0 Engineering/Math/Physics 25: Computational Methods 25 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt DeMorgan in MATLAB Work Problem 14 → Case-b A B A B ? >> % case-b >> y = 3 y = 0 0 3 >> b1 = ~((y == 2)|(y > 5)) b1 = 1 1 1 >> b2 = (~(y == 2))&(~(y >5)) b2 = 1 Engineering/Math/Physics 25: Computational Methods 26 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Logical Opers Short-Circuit Definition Oper. Name Operator for scalar logical expressions. A&& B returns true if both A and B evaluate to true, and false if they do not. Does NOT evaluate the Second expression if the First evaluates to FALSE (B does matter if A is False → B-eval is Shorted) && ShortCkt AND || Operator for scalar logical expressions. A||B returns true if either A or B or both Short- evaluate to true, and false if they do not. Ckt OR Does NOT evaluate the Second expression if the First evaluates to TRUE (B does matter if A is True → B-eval Shorted) Engineering/Math/Physics 25: Computational Methods 27 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Short Circuit Example Avoid Occasional Division-by-Zero a = b = 73 >> b = 3 b = 3 >> x = (b ~= 0) & (a/b > 18.5) x = 1 >> x = (b ~= 0) && (a/b > 18.5) x = 1 0 >> x = (b ~= 0) & (a/b > 18.5) Warning: Divide by zero. x = 0 >> x = (b ~= 0) && (a/b > 18.5) x = 0 Engineering/Math/Physics 25: Computational Methods 28 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Precedence Operator Types Precedence Operator Type FIRST Parentheses; evaluated starting with the innermost pair SECOND Arithmetic operators and logical NOT (~); evaluated from left to right. THIRD FOURTH FIFTH Relational operators (<, ==, etc.); evaluated from left to right Logical AND (&) Logical OR (|) Engineering/Math/Physics 25: Computational Methods 29 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Logical Functions Logical Function Definition all(x) Returns a scalar, which is 1 if all the elements in the vector x are nonzero and 0 otherwise. all(A) Returns a row vector having the same number of columns as the matrix A and containing ones and zeros, depending on whether or not the corresponding column of A has all nonzero elements. any(x) Returns a scalar, which is 1 if any of the elements in the vector x is nonzero and 0 otherwise. any(A) Returns a row vector having the same number of columns as A and containing ones and zeros, depending on whether or not the corresponding column of the matrix A contains any nonzero elemnts finite(A) Returns an array of the same dimension as A with ones where the elements of A are finite and zeros elsewhere. Engineering/Math/Physics 25: Computational Methods 30 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt More Logical Functions Logical Function Definition Returns a 1 if A is a character array and 0 ischar(A) otherwise. Returns a 1 if A is an empty matrix and 0 isempty(A) otherwise Returns an array of the same dimension as A, isinf(A) with ones where A has ‘inf’ and zeros elsewhere. Returns an array of the same dimension as A with ones where A has ‘NaN’ and zeros isnan(A) elsewhere. (‘NaN’ stands for “not a number,” which means an undefined result.) Engineering/Math/Physics 25: Computational Methods 31 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt More Logical Functions Logical Function Definition Returns a 1 if A is a numeric array and 0 isnumeric(A) otherwise. Returns a 1 if A has no elements with isreal(A) imaginary parts and 0 otherwise. Converts the elements of the array A into logical(A) logical values Returns an array the same dimension as A and B; the new array has ones where either A xor(A,B) or B is nonzero, but not both, and zeros where A and B are either both nonzero or both zero Engineering/Math/Physics 25: Computational Methods 32 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt The find Function find(v) Computes an array containing the indices of the nonzero elements of the vector v. [u,v,w]=find(A) Computes the arrays u and v containing the row and column indices of the nonzero elements of the array A and computes the array w containing the values of the nonzero elements. • The array w may be omitted. Engineering/Math/Physics 25: Computational Methods 33 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Logical Ops and find Function For the Session >> x = [5, -3, 0, 0, 8];y = [2, 4, 0, 5, 7]; >> z = find(x&y) z = 1 2 5 Note that the find function returns the indices, and not the values. Engineering/Math/Physics 25: Computational Methods 34 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Logical Ops and find Fcn cont Remember, the find function returns the indices, and not the values. In the following session, note the difference between the result obtained by y(x&y) and the result obtained by find(x&y) in the previous slide. >>x = [5, -3, 0, 0, 8];y = [2, 4, 0, 5, 7]; >> values = y(x&y) values = 2 4 7 >> how_many = length(values) how_many = 3 Engineering/Math/Physics 25: Computational Methods 35 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt All Done for Today George Boole (1815 - 1864) Engineering/Math/Physics 25: Computational Methods 36 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Engr/Math/Physics 25 Appendix f x 2 x 7 x 9 x 6 3 2 Bruce Mayer, PE Licensed Electrical & Mechanical Engineer BMayer@ChabotCollege.edu Engineering/Math/Physics 25: Computational Methods 37 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Find Demo >> x = [5, -3, 0, 0, 8];y = [2, 4, 0, 5, 7]; >> u = x&y u = 1 1 0 0 1 >> v = x(u) v = 5 -3 8 >> w = y(u) w = 2 4 7 >> z = find(x&y) z = 1 2 5 Engineering/Math/Physics 25: Computational Methods 38 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt DeMorgan in MATLAB Work Problem 14 → Case-a: ~ A B A B ? >> % case-a >> x = 7 x = 1 1 7 >> a1 = ~((x < 10)&(x >= 6)) a1 = 0 0 0 >> a2 = (~(x < 10))|(~(x >= 6)) a2 = 0 Engineering/Math/Physics 25: Computational Methods 39 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt DeMorgan in MATLAB Work Problem 14 → Case-b ~ A B A B ? >> % case-b >> y = 3 y = 0 0 3 >> b1 = ~((y == 2)|(y > 5)) b1 = 1 1 1 >> b2 = (~(y == 2))&(~(y >5)) b2 = 1 Engineering/Math/Physics 25: Computational Methods 40 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Software Class Defined: A software module that provides both procedural and data abstraction. It describes a set of similar objects, called its instances A Software object is defined via its CLASS, which determines everything about an object. Objects are individual instances of a class. For example, you may create an object call Spot from class Dog. The Dog class defines what it is to be a Dog object, and all the "dog-related" messages a Dog object can act upon. Engineering/Math/Physics 25: Computational Methods 41 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt Software Objects & Classes http://www.softwaredesign.com/objects.html Object-oriented software is all about OBJECTS. An object is a "black box" which receives and sends messages. A black box actually contains code (sequences of computer instructions) and data (information which the instructions operates on). Traditionally, code and data have been kept apart. For example, in the C language, units of code are called functions, while units of data are called structures. Functions and structures are not formally connected in C. A C function can operate on more than one type of structure, and more than one function can operate on the same structure. • Not so for object-oriented software! In o-o (object-oriented) programming, code and data are merged into a single indivisible thing -- an object. This has some big advantages, as you'll see in a moment. But first, here is why SDC developed the "black box" metaphor for an object. A primary rule of object-oriented programming is this: as the user of an object, you should never need to peek inside the box! How are objects defined? An object is defined via its CLASS, which determines everything about an object. Objects are individual instances of a class. For example, you may create an object call Spot from class Dog. The Dog class defines what it is to be a Dog object, and all the "dog-related" messages a Dog object can act upon. Engineering/Math/Physics 25: Computational Methods 42 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_Programming-2.ppt