COMP 116: Introduction to Scientific Programming Lecture 28: Midterm #2 Review.
-
Upload
theresa-boone -
Category
Documents
-
view
221 -
download
0
Transcript of COMP 116: Introduction to Scientific Programming Lecture 28: Midterm #2 Review.
Conditional Logic
Conditional Programming
◦When you want to run some code only if some test (“condition”) is satisfied
◦Making choices between 2 or more options
◦if-else-end
Relational OperatorsTests relationship between two objects or arrays
What is the data type of the result of these operators?
Name Operators Examples
Equivalence
Equality
Inequality
Binary Operators
Less Than
Less Than or Equal
Greater Than or Equal
Greater Than
Relational OperatorsTests relationship between two objects or arrays
Result is always a logical data type (or an array of logical data types)
Name Operators Examples
Equivalence
Equality == 5 == 5, x == y
Inequality ~= 5 ~= 5, z == (x^2 + y^2)
Binary Operators
Less Than < 5 < 3, sin(2) < cos(y)
Less Than or Equal
<= 4 <= 4,
Greater Than or Equal
>= 7 >= 10
Greater Than > 10 > 7
Logical OperatorsBoolean operatorsName Operators Examples
Unary Operators
Logical Negation (NOT)
Binary Operators
Logical And (AND)Short circuit (AND)
Logical Or (OR)Short circuit (OR)
Exclusive Or (XOR)
Logical OperatorsBoolean operatorsName Operators Examples
Unary Operators
Logical Negation (NOT)
~ (3 == 5) = 1 (true)
Binary Operators
Logical And (AND)Short circuit (AND)
& or &&
5 & 7 = 1 (true)
Logical Or (OR)Short circuit (OR)
| or ||
0 | 1 = 1 (true)
Exclusive Or (XOR) XOR xor(8, 5) = 0 (false)
Operates on logical data types, also returns a logical result.
Other Logical ObjectsLogical Constants: true, falseLogical Functions: and(), or(), xor(), not()
Predicate Logic: any(), all()Conversion Function: logical()Test functions (is* functions)
◦Examples: isvarname(), iskeyword()String Comparison functions:
◦strcmp(), strcmpi(), strncmp(), strncmpi()
Two options for logical indexing
Use a logical vector ◦x = rand(1, 100);◦x(x > 0.5); % returns only those elements in x which satisfy test
Use the find() function◦y = find( x > 0. 5 ); ◦x( y ) % returns elements in x whose indices are in y
Conditional ExecutionMultiple chained tests
if <Test1> commands1; % T1 trueelseif <Test2> commands2; % T1 false T2 true
elseif <Test3> commands3; % T1,T2 false T3 true
else commands4; % all falseend
Text Output
disp(msg)- displays an array or text string◦disp(‘Derp');
error(msg) - displays an error message and aborts current function or script◦error('Value Out of Range');
Writing simple functionsfunction [o1, o2] = funcName( i1, i2 )
% function comments… % body (implementation)end• Can have multiple inputs and multiple outputs
function [] = funcName()function o1 = funcName()function o1 = funcName( i1 )function o1 = funcName( i1, i2 )function [o1, o2] = funcName( i1, i2,
i3)
Loops: for loop statementthe counted loop solution
for <varindex> = <start>:<stop><Body: do some work>
end
for <idx> = <start>:<step>:<stop><Body: do some work>
end
Loops: while loop statementthe conditional loop solution
while <test> <Body: do some work> <Update: make progress towards exiting loop>end• While loops are great if we don’t know how many times
we need to loop, but if we can write a test for when we’re done
• For this to work properly, the test needs to evaluate to a logical value
• The while loop will run as long as test evaluates to true
• The while loop does not have a built-in counter like the for-loop (if you want to count something, you need to implement the counter yourself)
Loops: Common pitfalls
While-loops:◦Counters not initialized
◦While-loop never terminates or gets never executed
◦Counter does not count all the way to the desired value: e.g., x<5 instead of x<=5
Common Idioms: Minimum value within a vector
minVal.m Remarks
function ret = minVal(v)ret = v(1);
for i=2:length(v) if (v(i)<ret) ret = v(i); endend
Initialize return value
Now loop through all the remaining onesCheck if current value is smaller It’s smaller, so this is the new minimum value
Common Idioms: Check if value is contained within vector
isInVector.m Remarks
function ret = InVector(v, val)ret = false;for i=1:length(v) if (v(i)==val) ret = true; endendend
Initialize return value to default: ‘false’Now loop over all candidate valuesCheck if current value is the desired oneYes, so change the return value
Practice: Rewrite this using a while loop
isInVector.m Remarks
function ret = InVector(v, val)ret = false;c = 1;while (~ret & i<=length(v)) if ( v(i)==val ) ret = true; end i = i+1;endend
Initialize return value to default: ‘false’Initialize counter for while loopStop looping when value was foundCheck if current value is the desired oneYes, so change the return valueIncrement the counter, otherwise may loop forever!
Common Idioms: Check if value is contained within vector
Note the two conditions, understand why this works
Common Idioms: Looping over a matrix• Use a nested for loop:
function ret = findMaxElement( A )sz = size(A);ret = A(1,1);
for i=1:sz(1) for j=1:sz(2) if ( A(i,j)>ret ) ret = A(i,j); end endend
Strings as a vector of charsCan be manipulated like any other
vector
s1 = 'The quick brown fox 's2 = 'jumped over the lazy dog'
s = [s1 s2] % concatenate stringss(5) % ans = qs(17:19) % ans = foxjIdx = find( s == 'j' )jStr = s(jIdx:jIdx+3) % ans = jump
String Comparison
Avoid normal comparison operators!◦s1 == s2, s1 < s3, s1 >= s3◦Operators work element by element (on
characters)◦Thus, strings (i.e., the vector of chars) must
be same length
Use string comparison functions instead◦strcmp(), string comparison◦strcmpi, string comparison while ignoring
case◦strncmp, strncmpi:
Similar, but compares first n characters only
String Searching
strfind◦Search for a string inside another
string◦returns indices to start of each
instancestrVal = [‘with great power comes great responsibility.’];
strfind( strVal, ‘great’)
% ans = [6 24]
String Replacement
strrep
strVal = [‘with great power comes great responsibility.’];
strrep( strVal, ‘great’, ‘no’)