Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP 116: Introduction to Scientific Programming Lecture 28: Midterm #2 Review.

Similar presentations


Presentation on theme: "COMP 116: Introduction to Scientific Programming Lecture 28: Midterm #2 Review."— Presentation transcript:

1 COMP 116: Introduction to Scientific Programming Lecture 28: Midterm #2 Review

2 Announcements Midterm in SN014

3 Topics Conditional Logic Writing Simple Functions Variables, workspaces, scope Loops Strings

4 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

5 Relational Operators Tests relationship between two objects or arrays What is the data type of the result of these operators? NameOperatorsExamples Equivalence Equality Inequality Binary Operators Less Than Less Than or Equal Greater Than or Equal Greater Than

6 Relational Operators Tests relationship between two objects or arrays Result is always a logical data type (or an array of logical data types) NameOperatorsExamples 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

7 Logical Operators Boolean operators NameOperatorsExamples Unary Operators Logical Negation (NOT) Binary Operators Logical And (AND) Short circuit (AND) Logical Or (OR) Short circuit (OR) Exclusive Or (XOR)

8 Logical Operators Boolean operators NameOperatorsExamples 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)XORxor(8, 5) = 0 (false) Operates on logical data types, also returns a logical result.

9 Other Logical Objects Logical Constants: true, false Logical 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 ()

10 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

11 Conditional Execution Multiple chained tests if commands1; % T1 true elseif commands2; % T1 false T2 true elseif commands3; % T1,T2 false T3 true else commands4; % all false end

12 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');

13 Writing simple functions function [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)

14 Scope Functions run in their own ‘workspaces’ MATLAB sq.m x =4 x2 =16 foo =4 x2 =5 bar =16

15 Scripts vs. Functions

16 Loops: for loop statement the counted loop solution for = : end for = : : end

17 Loops: while loop statement the conditional loop solution while 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)

18 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

19 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); end Initialize return value Now loop through all the remaining ones Check if current value is smaller It’s smaller, so this is the new minimum value

20 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; end Initialize return value to default: ‘false’ Now loop over all candidate values Check if current value is the desired one Yes, so change the return value Practice: Rewrite this using a while loop

21 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; end Initialize return value to default: ‘false’ Initialize counter for while loop Stop looping when value was found Check if current value is the desired one Yes, so change the return value Increment the counter, otherwise may loop forever! Common Idioms: Check if value is contained within vector Note the two conditions, understand why this works

22 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

23 Strings as a vector of chars Can be manipulated like any other vector s1 = 'The quick brown fox ' s2 = 'jumped over the lazy dog' s = [s1 s2] % concatenate strings s(5) % ans = q s(17:19) % ans = fox jIdx = find( s == 'j' ) jStr = s(jIdx:jIdx+3) % ans = jump

24 String Comparison Avoid normal comparison operators! ◦s1 == s2, 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

25 String Searching strfind ◦ Search for a string inside another string ◦ returns indices to start of each instance strVal = [‘with great power comes great responsibility.’]; strfind( strVal, ‘great’) % ans = [6 24]

26 String Replacement strrep strVal = [‘with great power comes great responsibility.’]; strrep( strVal, ‘great’, ‘no’)

27 Summary Practice, practice, practice ◦ Work through the examples done in class


Download ppt "COMP 116: Introduction to Scientific Programming Lecture 28: Midterm #2 Review."

Similar presentations


Ads by Google