Upload
earl-harrison
View
216
Download
2
Tags:
Embed Size (px)
Citation preview
[email protected] • ENGR-25_Programming-2.ppt1
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
Bruce Mayer, PELicensed Electrical & Mechanical Engineer
Engr/Math/Physics 25
Chp4 MATLAB
Programming-2
[email protected] • ENGR-25_Programming-2.ppt2
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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
[email protected] • ENGR-25_Programming-2.ppt3
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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
[email protected] • ENGR-25_Programming-2.ppt4
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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.
[email protected] • ENGR-25_Programming-2.ppt5
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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.
[email protected] • ENGR-25_Programming-2.ppt6
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
1st Computer Bug – Circa 1945
attributed to Grace Hopper, who publicized the cause of a malfunction in an early electromechanical computer
[email protected] • ENGR-25_Programming-2.ppt7
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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.
[email protected] • ENGR-25_Programming-2.ppt8
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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
[email protected] • ENGR-25_Programming-2.ppt9
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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
[email protected] • ENGR-25_Programming-2.ppt10
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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
[email protected] • ENGR-25_Programming-2.ppt11
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
ReCall RELATIONAL OperatorsSymbol 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”
[email protected] • ENGR-25_Programming-2.ppt12
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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
relational operators can be used for array addressing• With x & y as before
• finds all the elements in x that are less than the corresponding elements in y– e.g. x(1) = 6
>> z = x(x<y)z = 6
[email protected] • ENGR-25_Programming-2.ppt13
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
Operator Precedence
The arithmetic operators +, -, *, /, and \ have precedence over the relational operators
Thus the statement
z = 5 > 2 + 7
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
• Is Equivalent to
z = 5 >(2+7)
• Returns Result z = 0
[email protected] • ENGR-25_Programming-2.ppt14
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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)
[email protected] • ENGR-25_Programming-2.ppt15
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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.
[email protected] • ENGR-25_Programming-2.ppt16
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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.
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.
[email protected] • ENGR-25_Programming-2.ppt17
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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
>> B = logical(eye(3))B = 1 0 0 0 1 0 0 0 1
Extract the diagonal elements of A
>> C = A(B)C = 5 9 13
[email protected] • ENGR-25_Programming-2.ppt18
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
Logical Operators for Arrays
Oper. Name Definition
~ NOT~A returns an array the same dimension as A; the new array has ones where A is zero and zeros where A is nonzero
& AND
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
| OR
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.
[email protected] • ENGR-25_Programming-2.ppt19
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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 NOT (inverter)
Input = 1 Output = 0
Input = 0 Output = 1
AND (all high = high, else low)
Input 1 Input 2 Output
0 0 0
0 1 0
1 0 0
1 1 1
OR (any high = high, else low)
Input 1 Input 2 Output
0 0 0
0 1 1
1 0 1
1 1 1
[email protected] • ENGR-25_Programming-2.ppt20
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
Venn Diagrams for Booleans
AND Operator• ALL Terms are
Present
• AND represents the INTERSECTION (∩) of Sets
OR Operator• ANY ONE of the
terms are present
• OR represents the UNION (U) of Sets
[email protected] • ENGR-25_Programming-2.ppt21
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
Xor → EXCLUSIVE or
MATLAB SynTax
xor Evaluates as TRUE Only If EACTLY ONE of A or B is True, but NOT BOTH
Xor Truth TableC = xor(A, B) 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• Xor Venn Diagram
[email protected] • ENGR-25_Programming-2.ppt22
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
Other Logic Gates NAND ~&
• “Not AND”
NANDs & NORs are easier to implement in HARDWARE than are ANDs & ORs• i.e., They take Fewer Transistors
NOR ~|• “Not OR”
NAND (all high = low, else high)
Input 1 Input 2 Output
0 0 1
0 1 1
1 0 1
1 1 0
NOR (any high = low, else high)
Input 1 Input 2 Output
0 0 1
0 1 0
1 0 0
1 1 0
[email protected] • ENGR-25_Programming-2.ppt23
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
Boolean Algebra
Boolean Logic can be Mathematically Formalized with the use of Math Operators
The Math Operators Corresponding to Boolean Logic Operations:
• A and B can only be TRUE or FALSE• TRUE represented by 1; FALSE by 0
Operator Usage Notation
AND A AND B A.B or A·B
OR A OR B A+B
NOT NOT A ~A or A
[email protected] • ENGR-25_Programming-2.ppt24
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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 Verify DeMorgan in
MATLAB
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
[email protected] • ENGR-25_Programming-2.ppt25
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
DeMorgan in MATLAB
Work Problem 14 → Case-a:
>> % case-a
>> x = 7x = 7>> a1 = ~((x < 10)&(x >= 6))a1 = 0>> a2 = (~(x < 10))|(~(x >= 6))a2 = 0
11
0 0
BABA ?
[email protected] • ENGR-25_Programming-2.ppt26
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
DeMorgan in MATLAB
Work Problem 14 → Case-b
>> % case-b
>> y = 3y = 3>> b1 = ~((y == 2)|(y > 5))b1 = 1>> b2 = (~(y == 2))&(~(y >5))b2 = 1
00
1 1
BABA ?
[email protected] • ENGR-25_Programming-2.ppt27
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
Logical Opers Short-CircuitOper. Name Definition
&&Short-
Ckt AND
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)
|| Short-Ckt OR
Operator for scalar logical expressions. A||B returns true if either A or B or both evaluate to true, and false if they do not. Does NOT evaluate the Second expression if the First evaluates to TRUE (B does matter if A is True → B-eval Shorted)
[email protected] • ENGR-25_Programming-2.ppt28
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
Short Circuit Example
Avoid Occasional Division-by-Zeroa = 73>> b = 3b = 3>> x = (b ~= 0) & (a/b > 18.5)x = 1>> x = (b ~= 0) && (a/b > 18.5)x = 1
b = 0>> x = (b ~= 0) & (a/b > 18.5)Warning: Divide by zero.x = 0>> x = (b ~= 0) && (a/b > 18.5)x = 0
[email protected] • ENGR-25_Programming-2.ppt29
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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 Relational operators (<, ==, etc.); evaluated from left to right
FOURTH Logical AND (&)
FIFTH Logical OR (|)
[email protected] • ENGR-25_Programming-2.ppt30
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
Logical FunctionsLogical
FunctionDefinition
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.
[email protected] • ENGR-25_Programming-2.ppt31
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
More Logical FunctionsLogical
Function Definition
ischar(A) Returns a 1 if A is a character array and 0 otherwise.
isempty(A) Returns a 1 if A is an empty matrix and 0 otherwise
isinf(A)Returns an array of the same dimension as A, with ones where A has ‘inf’ and zeros elsewhere.
isnan(A)
Returns an array of the same dimension as A with ones where A has ‘NaN’ and zeros elsewhere. (‘NaN’ stands for “not a number,” which means an undefined result.)
[email protected] • ENGR-25_Programming-2.ppt32
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
More Logical Functions
LogicalFunction Definition
isnumeric(A)
Returns a 1 if A is a numeric array and 0 otherwise.
isreal(A) Returns a 1 if A has no elements with imaginary parts and 0 otherwise.
logical(A) Converts the elements of the array A into logical values
xor(A,B)
Returns an array the same dimension as A and B; the new array has ones where either A or B is nonzero, but not both, and zeros where A and B are either both nonzero or both zero
[email protected] • ENGR-25_Programming-2.ppt33
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
The find Function
find(v)
[u,v,w]=find(A)
Computes an array containing the indices of the nonzero elements of the vector v.
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.
[email protected] • ENGR-25_Programming-2.ppt34
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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.
[email protected] • ENGR-25_Programming-2.ppt35
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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
[email protected] • ENGR-25_Programming-2.ppt36
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
All Done for Today
George Boole(1815 - 1864)
[email protected] • ENGR-25_Programming-2.ppt37
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
Bruce Mayer, PELicensed Electrical & Mechanical Engineer
Engr/Math/Physics 25
Appendix 6972 23 xxxxf
[email protected] • ENGR-25_Programming-2.ppt38
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
Find Demo>> x = [5, -3, 0, 0, 8];y = [2, 4, 0, 5, 7];>> u = x&yu = 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
[email protected] • ENGR-25_Programming-2.ppt39
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
DeMorgan in MATLAB
Work Problem 14 → Case-a:
>> % case-a
>> x = 7x = 7>> a1 = ~((x < 10)&(x >= 6))a1 = 0>> a2 = (~(x < 10))|(~(x >= 6))a2 = 0
11
0 0
BABA ?
~
[email protected] • ENGR-25_Programming-2.ppt40
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
DeMorgan in MATLAB
Work Problem 14 → Case-b
>> % case-b
>> y = 3y = 3>> b1 = ~((y == 2)|(y > 5))b1 = 1>> b2 = (~(y == 2))&(~(y >5))b2 = 1
00
1 1
BABA ?
~
[email protected] • ENGR-25_Programming-2.ppt41
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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.
[email protected] • ENGR-25_Programming-2.ppt42
Bruce Mayer, PE Engineering/Math/Physics 25: Computational Methods
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.