300 likes | 423 Vues
In this lecture on MATLAB programming, we dive into logical expressions and selection statements. We start with a recap of what we have learned, including plotting and arithmetic. The focus of today’s session is on adapting our programming plans at runtime. We will explore conditional programming using `if`, `else`, and `switch` statements. Additionally, we will cover logical and relational operators, logical expressions, and common pitfalls. This session is crucial for understanding how to make decisions in your MATLAB programs and effectively manage logic in your code.
E N D
COMP 116: Introduction to Scientific Programming Lecture 14: Logical Expressions Selection Statements
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) ?
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!');
What we are going to learn • Conditional programming • if else end • switch • Review • Logical operators • Relational operators • Logical Expressions (Conditions, Tests) • Common Pitfalls
Relational OperatorsTests relationship between two objects or arrays • Result is true/false (one or zero) or array of true/false
Logical OperatorsBoolean operators • Performs binary logic on two logical data type operands (or arrays) to return a logical result.
Boolean LogicTruth Tables Logical operators allow us to build up compound tests, piece by piece
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
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)))
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()
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)
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
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
Example:display random number only if it is less than .5 randomValue = rand; if (randomValue < .5) % Display result disp( randomValue); end
IFstatementTwo alternatives, if <true> else <false> end • Syntax: if <test> commands1; % True else commands2; % False end
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);
Conditional ExecutionMultiple chained tests if <Test1> commands1; % T1 true elseif <Test2> commands2; % T2 true elseif <Test3> commands3; % T3 true else commands4; % all false end
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]);
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
A note on formatting Bad Good
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
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.
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
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
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
Reminder • Practice using conditional logic • Logical expressions • If statement • Switch statement • Review slides on conditional logic