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: _____ (false) and ____ (true) + logical operators: __ (and), __ (or), __ (not), ___ (exclusive or) + truth tables: AND OR NOT & 0 1 | 0 1 ~ +---+---+ +---+---+ +---+---+ 0 | | | 0 | | | | | | +---+---+ +---+---+ +---+---+ 1 | | | 1 | | | | | | +---+---+ +---+---+ +---+---+ + relational operators: >, >=, <, <=, ==, ~= + examples) >> 1 < 2 % >> 1 == 1 % >> 1 == 2 % >> 1==1 & 2==2 % >> 1 > 2 | 1 < 2 % >> xor(1 < 2,1 < 3) % ------------------------------------------------------------------------------- (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 + To extract elements that correspond to TRUE relations, use array(logicalarray). Example) >> x(y) 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$ + 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..... To fix, use $logical$ function: >> z(logical(q)) -------------------------------------------------------------------------------