CS99, Fall 2002 Lecture 5, Mon 9/23 ------------------------------------------------------------------------------- Announcements: + updates to website + H3 will posted + continue reading: Chapter 4 ------------------------------------------------------------------------------- (0) Topics + advice about communication + more about boolean things + more about selection statements + nested selection statements + logical arrays ------------------------------------------------------------------------------- (1) Logic + Boolean: test logical TRUTH or FALSEHOOD + Boolean Expressions: expressions with boolean values and operators + logical values: 0 (false) and 1 (true) + logical operators: & (and), | (or), ~ (not), xor (exclusive or) + truth tables: AND OR NOT & 0 1 | 0 1 ~ +---+---+ +---+---+ +---+---+ 0 | 0 | 0 | 0 | 0 | 1 | | 0 | 1 | +---+---+ +---+---+ +---+---+ 1 | 0 | 1 | 1 | 1 | 1 | | 1 | 0 | +---+---+ +---+---+ +---+---+ + relational operators: >, >=, <, <=, ==, ~= + examples) >> 1 < 2 % less than >> 1 == 1 % equal (true) >> 1 == 2 % equal (false) >> 1==1 & 2==2 % true >> 1 > 2 | 1 < 2 % true >> xor(1 < 2,1 < 3) % false ------------------------------------------------------------------------------- (2) Selection statements + General form of the $if$ statement is IF expression statements ELSEIF expression statements ELSE statements END + Must have $if$ and $end$ + $else$ and $elseif$s are optional + see also $switch$ ------------------------------------------------------------------------------- (3) Nested selection statements + Any of the statements portion of the "statements" in the if-syntax can be ... you guessed it ... any legal statement! + So, you can have more if-statements "inside another if! ------------------------------------------------------------------------------- (4) Logical Arrays (see pg 157) + an array of logical values + operations are applied to each element one at a time + MATLAB stores 1 or 0 depending on the truth of the relation for each element + example) >> x = [1 2 3]; >> y = x >= 2 y = 0 1 1 + To extract elements that correspond to TRUE relations, use array(logicalarray). + example) >> x(y) ans = 2 3 + example) Find even integers from an array. >> z = 0:10; % array from 0 to 10 >> k = mod(z,2)==0; % $k$ is a logical array >> z(k) % extract even integers from $k$ ans = 0 2 4 6 8 10 + WARNING: To generate logical array, MUST use relations, not just enter 0 and 1! + example) >> z=3:5; % array of ints from 3 to 5 >> q=[0 1 0]; % array of what appears to be logical values (but isn't!) >> z(q) % attempt to extract elements from $z$ (but won't work) output is the error mesg: ??? Index into matrix is negative or zero. See release notes on changes to logical indices. To fix, use $logical$ function: >> z(logical(q)) ans = 4 -------------------------------------------------------------------------------