 Download Download Presentation COMP 116: Introduction to Scientific Programming

# COMP 116: Introduction to Scientific Programming

Download Presentation ## COMP 116: Introduction to Scientific Programming

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
##### Presentation Transcript

1. COMP 116: Introduction to Scientific Programming Lecture 14: Logical Expressions Selection Statements

2. Programming: what we’ve seen so far • Doing things using Matlab • plotting, arithmetic etc. • Plan a sequence of commands for Matlab to execute • Linear programming, regression, systems • Today: What if the plan needs to change on the fly (at runtime) ?

3. Programming: making choices % Define a secret number, make the user guess it secret = 7; guess = input(“Guess the number: ”); -- if the guess is less than secret-- disp(`Too low.'); -- if the guess is greater than secret-- disp(`Too high.'); -- otherwise -- disp(`You win!');

4. What we are going to learn • Conditional programming • if else end • switch • Review • Logical operators • Relational operators • Logical Expressions (Conditions, Tests) • Common Pitfalls

5. Relational OperatorsTests relationship between two objects or arrays • Result is true/false (one or zero) or array of true/false

6. Logical OperatorsBoolean operators • Performs binary logic on two logical data type operands (or arrays) to return a logical result.

7. Boolean LogicTruth Tables

8. Boolean LogicTruth Tables

9. Boolean LogicTruth Tables

10. Boolean LogicTruth Tables Logical operators allow us to build up compound tests, piece by piece

11. Logical OperatorsBoolean operators Short circuiting • &&and || are like & and |, except that they can “short-circuit” the second argument. • a & b always evaluates both a and b • a && b first evaluates a, and if false, ignores b

12. Logical Expressions • Simple or complex expression whose final result is a single true/false logical result (or array of logicals). • Try: >> x=3, y=4, z=5 >> x == 3 >> (x+y) < z >> z.^2 >= (x.^2 + y.^2) >> (ones(4,5)) <= (rand(4,5).*2) >> ((x+y) < z) && (a.^2 >= (x.^2 + y.^2)))

13. Other Logical Objects • Functions or objects which return logical data types as their output • Logical Functions: and(), or(), xor(), not() • Predicate Logic: any(), all() • Test functions (is*functions) • isvarname(), iskeyword() • String Comparison functions: • strcmp(), strcmpi(), strncmp(), strncmpi()

14. Logical Objects • >> B = [0.53 0.67 0.01 0.38 0.07 0.42 0.69] >> all(B) • >> x = rand(1,7) * 5; >> any(x > 3)

15. Logical Indexing • Use a logical vector as an index into an array of elements • x = rand(1, 20); • x(x > 0.5); % returns only those elements in x which satisfy test • find() function • y = find( x > 0. 5 ); • x( y ) % returns elements in x which satisfy test

16. CONDITIONAL ProgrammingSelection Statements

17. IF StatementSingle conditional path • Syntax: • For <test>, use logical expressions that evaluate to a single true/false value. if <test> commands; % 1 or more end

18. Example:display random number only if it is less than .5 randomValue = rand; if (randomValue < .5) % Display result disp( randomValue); end

19. IFstatementTwo alternatives, if <true> else <false> end • Syntax: if <test> commands1; % True else commands2; % False end

20. Exercise:Display absolute value % Implement our own absolute value % inVal= |inVal| % inVal should already be assigned % Is input value negative ? if (inVal < 0) % Parenthesis optional outVal = -inVal; % Invert negative else outVal = inVal; % Keep positive end disp(outVal);

21. Conditional ExecutionMultiple chained tests if <Test1> commands1; % T1 true elseif <Test2> commands2; % T2 true elseif <Test3> commands3; % T3 true else commands4; % all false end

22. Example: grade assignment % score should be preassigned if (score >= 91) grade = 'A'; elseif (score >= 81) grade = 'B'; elseif (score >= 71) grade = 'C'; elseif (score >= 61) grade = 'D'; else grade = 'F'; end disp([‘grade is’ grade]);

23. Conditional ExecutionNested conditions if <Test1> if <Test2> commands1; % T1,T2 both true else commands2; % T1=1, T2=0 end else if <Test3> commands3; % T1=0, T3=1 else commands4; % T1,T3 both false end end

24. A note on formatting Bad Good

25. Exercise: Test 2D Point in 2D Box % Tests 2D point is contained in a 2D box box_bottom_left_corner=[10 20]; box_top_right_corner=[15 30] Point_x=input(‘X-coordinate: ‘); Point_y=input(‘Y-coordinate: ‘); % display “in the box” or “not in the box” % Use if/else xMin=box_bottom_left_corner(1); yMin=box_bottom_left_corner(2); xMax=box_top_right_corner(1); yMax=box_top_right_corner(2); if (Point_x < xMin) || (Point_x > xMax) res = false; % Outside box else if (Point_y < yMin) || (Point_y > yMax) res = false; % Outside box else res = true; % Inside Box end end

26. switch statement switch <switch_expr> case <case_expr> commands1; % case 1 case {expr2, expr3, … } commands2; % case 2 otherwise commands3; % all other cases end • Executes one set of commands from a set of command choices • Each alternate set of commands is called a case.

27. Example: Polygon Shapes shape = input(‘Enter a shape: ‘); switch shape case 'triangle' disp('3-sided polygon'); case {'square', 'rectangle'} disp('4-sided polygon'); case 'circle' disp('infinite sides'); otherwise disp('unknown shape'); end

28. Common Pitfalls • Using = instead of == and vice versa. • if x = 5 … % Error, use if x == 5 • x == [2 3] % Error, use x = [2 3] • Confusing && and || • Confusing || and XOR • Inserting an extra space in a 2 character relational operator • if x <= y % Error, note extra space • if x <= y % Correct

29. Common Pitfalls, contd. • Using multiple comparisons properly • 10 <= x <= 100 % Error • (10 <= x) && (x <= 100) % Correct • Forgetting the quotes when working with characters or strings • if letter == y % Error • if letter == 'y' % Correct • Comparing characters / strings • 'c' < 'Z' % OK, compatible sizes • 'cat' < 'catch' % Error, size problem • strcmp('cat', 'catch') % Use strcmp

30. Reminder • Practice using conditional logic • Logical expressions • If statement • Switch statement • Review slides on conditional logic