Weizmann 2010 © 1 Introduction to Matlab & Data Analysis Tutorial 6: Boolean Logic, Flow Control...

Post on 21-Dec-2015

225 views 0 download

Transcript of Weizmann 2010 © 1 Introduction to Matlab & Data Analysis Tutorial 6: Boolean Logic, Flow Control...

Weizmann 2010 © 1

Introduction to Matlab & Data Analysis

Tutorial 6: Boolean Logic, Flow Control

and the debuggerPlease change directory to directory E:\Matlab (cd E:\Matlab;)

From the course website

(http://www.weizmann.ac.il/midrasha/courses/MatlabIntro//course_outline.htm )

Download:

debugExample.m, drawGasPrices.m, tryCatch.m, gas.mat,

Shown on board:

t6.m , trueOrFalse.m , rockPaperScissors.m, , estimatingEpsilon.m

2

Topics Boolean logic

Relational and logical operators What is true and what is false

Flow control: if-else-end constructions Switch-case-end constructions for loops while loops Loops flow control:

break continue

try-catch retrun

First use of Matlab debugger

Weizmann 2010 © 3

Lecture Reminder

4

What is true and what is false?

Type “logical” True represented by 1 False represented by 0

Keywords: true, false. What is False?

false 0

What is true? anything else … Special cases:

Empty string ‘’ Array with false values [1 0 1] Empty matrix []

What About NaN? Not true and not false – NaN if (NaN)??? NaN's cannot be converted to logicals.

5

Reminder - Relational operators

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

== Equal to

~= Not equal to

Element by element: Similar dimensions Scalar expansion

6

Reminder - Logical Operators

Logical functions(column-wise) any(x) all(x)

Logical operator

Description

&& And (short-circuiting)

|| OR (short-circuiting)

~ Notx y X && Y x || y

0 0 0 0

0 1 0 1

1 0 0 1

1 1 1 1

x ~x

0 1

1 0

xor(x,y)

0

1

1

0

Logical operator

Description

& And

| OR

~ Not

7

Reminder - Flow Control Flow control:

if-else-end constructions

switch-Case constructions

For loops While loops Loops flow control:

Break continue

Return Try-Catch

If road == the_one_less_traveled_bydisp(‘Made all the difference’);

Elsedisp(‘Kept for another day’);

end

8

Reminder - If-else-end constructions

if (expression I) statement1a; statement1b;

elsestatement2a;statement2b;

end

if (expression I) statement1a; statement1b;

elseif (expression II) statement2a;statement2b;

elseif (expression III) statement3a;statement3b;

elsestatement4a;statement4b;

end

Use indentation!

9

Switch-Case constructions

if (expression I) statement1a; statement1b;

elseif (expression II) statement2a;statement2b;

elseif (expression III) statement3a;statement4b;

end

switch expression case test_exp1

statement1a; statement1b;

case {test_exp2, test_exp3} statement1a; statement1b;

otherwise statement1a; statement1b;

end

Scalar: expression == test_exp1

String: strcmp(expression, test_exp1)

10

Example - Switch-Caseday='Tue';switch day case 'Mon' disp('Matlab class'); case {'Tue','Wed','Thu'} disp('Matlab tutorial'); otherwise disp('Free');end

11

Reminder - For and While Loops

In every iteration of the loop the index equals to one column of the array.

for index = array statement1;statement2;

end

while expression statement1;statement2;

end

If the expression is true -> run another iteration

Pitfall – endless loop

12

Reminder - Nested loops

for index1 = array1 statement1;statement2;for index2 =

array2 statement3;statement4;

endend

Indentation! No limitations of nesting order and # levels

for index1 = array1 statement1;statement2;while expression

statement3;statement4;if expression1

statement5;end

endend

13

Reminder - Break, Continue and return affect the flow break – immediately breaks

the loop Breaks only one loop

continue – jump to the end statement. Does not break the loop

return – returns control to the command line (or to the calling function).

On

ly in

sid

e

loop

s!

An

yw

her

e

Weizmann 2010 © 14

End Of lecture Reminder

Weizmann 2010 © 15

Boolean Logic

16

Boolean Logic - Pitfalls

Comparing to empty array gives empty array

Use isempty(A)

a = []; b = []; c = 1;

a == ba == c

NaN == NaN

2 = 2

NaN is not equal to itself. Use isnan.

Major Pitfall! = ~= ==

Empty array

Empty array

Error

17

Use Indentation & Parenthesesx = 0; y = 1; z = 2;

% The statement below is unclearx^2 - y == -1 && y*2 - z == 0 || z*2 - x == 5

% Use parentheses! % Use Indentation – % Do not split a logical expression into two lines( (x^2 - y == -1) && … (y*2 - z == 0 ) ) || … (z*2 - x == 5)

Weizmann 2010 © 18

Flow controlExamples: if-else-end for loops while loops (break, continue)

19

Example - Rock-Paper- Scissors

%%Paper-Rock-Scissors% we use % P for Paper% R for Rock% S for Scissors % get players handsclc;player1_hand = input('Player 1 hand:');clc;player2_hand = input('Player 2 hand:');clc; disp(['Player 1 hand is: ' player1_hand]); disp(['Player 2 hand is: ' player2_hand]);

How do we compute

who won? Ideas?

Hint: use strcmp

20

If Example – Rock-Paper- Scissors

%Calculate who wonif ( ( strcmp(player1_hand,'P') && strcmp(player2_hand,'R') ) || ... ( strcmp(player1_hand,'R') && strcmp(player2_hand,'S') ) || ... ( strcmp(player1_hand,'S') && strcmp(player2_hand,'P') ) )

disp('Player 1 won!');

elseif ( ( strcmp(player2_hand,'P') && strcmp(player1_hand,'R') ) || ... ( strcmp(player2_hand,'R') && strcmp(player1_hand,'S') ) || ... ( strcmp(player2_hand,'S') && strcmp(player1_hand,'P') ) )

disp('Player 2 won!');

else disp('Draw');end

rockPaperScissors.m

Notice the indentation

21

Simple For Loop Example – Using For Loops to Initiate Matrices

x = zeros(1,10);prev_num = 0; for i=1:10 x(i) = i + sqrt(prev_num); prev_num = x(i);end

Using a for loop create a 1x10 vector where each entry is the sum of its index and the square root of the previous element (the “zero” element value is 0)

Allocating memory

“end case”: i=1

variables naming: prev_, cur_

22

Simple For Loop Example – Using For Loops to Initiate Matrices

x = zeros(1,10); for i=1:10 if (i == 1) % end case first element x(i) = i; else x(i) = i + sqrt(x(i-1)); endend

Alternative code:

Using if-else-end to take care of end cases

23

Nested For Loop Example – Using For Loops to Initiate Matrices

A = zeros(3,3); for n = 1:3 for m = 1:3 A(n,m) = n^2 + m^2; endend

A =

2 5 10 5 8 13 10 13 18

% Don’t forget to allocate memory!

Using for loops initiate a 3x3 matrix such that:

Each entry is the sum of its subscripts square

24

While Loop Example –Estimating Epsilon

Epsilon – the smallest number that can be added to 1 such that the result is greater than 1.

my_eps= 1; while (my_eps+1) > 1 my_eps = my_eps/2;end

my_eps = my_eps*2;

Is that ok?

Can we compute the last line inside the loop?

my_eps = 1; while (my_eps+1) > 1 my_eps = my_eps/2; if (my_eps+1) <= 1 my_eps = my_eps*2; break; endendestimatingEpsilon.m

25

Efficiency And Readability

Usually when operations can be performed by either loops or vector operation – the vector operations are more efficient and readable.

Always allocate memory in advance.

y = sin(x);

x = linspace(0,2*pi,1000);

z = zeros(size(x)); for i=1:length(x) z(i) = sin(x(i));end

==

Weizmann 2010 © 26

The Debugger

27

Debugger

Debugging – The process of discovering and correcting bugs in a program

Matlab has a graphical debugger We use the debugger to follow a

specific run of the control flowdebugExample.m

/2

*2A B

28

Debugging Run Time Errors

Open the example: edit debugExample.m;

Debug buttons Debug menu Stop if errors / warn Break points –

Red Gray Modifying a file

There are bugs

Lets find them . .

29

Coding Tips

An “end case” – a relatively rare input that might cause bugs (NaN, Inf).

Use indentation: Write the “end” before writing the content Cntl-I

Use variables instead of numbers (avoid “hard coding”)

Weizmann 2010 © 30

Throwing and Catching errors

error(‘msg’);try – catch - end

31

Try-Catchtry

statement1;errorstatement2;…

catchstatement3;statement4;…

end

Try to run the code in the “try” block

If no error and reached the catch, go to the end statement.

If an error occur, go to the catch statement.

32

Try-Catch - Errorstry

statement1;

error(‘error message’); statement2;

catch

statement3;

errorStr = lasterr;

disp(errorStr);

statement4;

end

error_string = lasterr;

error = lasterror;

error.message

rethrow(lasterror);

Using the error

Structure, next tutorials…

Many Matlab functions throw errors when something goes wrong

You can throw error: error(‘error message’);

You can also catch errors:

33

Try and Catch Exampletry A = ones(3,3); x = input('Input a number by which A will be divided:'); if isnan(x) error(['NaN was entered: ' num2str(x)]); end A = A /x; A catch errorStr = lasterr; disp(errorStr); %rethrow(lasterror);end

Input: 2A = 0.5000 0.5000 0.5000 0.5000 0.5000 0.5000 0.5000 0.5000 0.5000

Input: nanError using ==> TryCatch at 7NaN was entered: NaN

Input:[0, 1]Error using ==> mrdivideMatrix dimensions must agree.Try to uncomment

TryCatch.m

34

Final Example –Drawing multiple plots

File edit drawGasPrices.m you should have gas.mat in the same directory

Reminder: Gasoline_prices – US gas prices at each month

of the years 1976-2004 Years – 1976:2004 Months – char matrix. Each row contains a

month

35

Final Example –Drawing multiple plots

Goal: Get from the user at most five years Draw a figure with a subplot for every year The year subplot displays the prices of gas

during this year as a function of the months.

1. Load the data

Make sure the data is

OK

2. Getting which

years to draw

3. Draw the

plot

36

Final Example –Drawing multiple plots

Notice: Errors:

Throwing for error Try-catch to avoid error exit when the input is wrong

Using while, return, break, continue to get input

Using For loop: Using the loop index to retrieve relevant data Using index to set current subplot Variables naming

Use the debugger to go over the code

37

Drawing Multiple Plots – Throwing Error

clear; close all;load gas.mat; % checking that the data existif (~exist('gasoline_prices','var') || ... ~exist('months','var') || ... ~exist('years','var') ) error('gasoline_prices ... not defined');end

1. Load the data

Make sure the data is

OK

38

Drawing Multiple Plots – Displaying Instructions to the User

% getting which years to drawyears2draw = []; disp('Enter which year to draw')disp('Years should be between 1976 and 2004');disp('Maximum five years are allowed.');

disp('When done enter D');

disp('If you wish to quit without drawing enter Q');

D while mean break

Q while mean return

2. Getting which years to

draw

39

Drawing Multiple Plots – Quitting and Breaking a Loop

while length(years2draw) < 5 …

cur_year = [input('Year / D / Q :','s')]; if (strcmp(cur_year, 'Q')) disp('Bye!'); return; elseif (strcmp(cur_year, 'D')) break; end …end

2. Getting which years to

draw

Use while to iterate until you get a satisfying input

40

Drawing Multiple Plots –Using Continue, for mal input

while length(years2draw) < 5…

% getting the number cur_year = str2num(cur_year); cur_year = floor(cur_year); if ~isscalar(cur_year) disp('Input is not a number, try again.'); continue; end

% year not in range if (cur_year < 1976 || cur_year > 2004) disp('Years are not … 1976-2004'); continue; end years2draw(end+1) = cur_year;end

2. Getting which years to

draw

41

Drawing Multiple Plots – Try-Catch Handling of unpredicted error

while length(years2draw) < 5 … try <all the code of getting the input>

% adding the year to the input years vector years2draw(end+1) = cur_year;

catch

error_str = lasterr;

disp(['Bad input, try again:' error_str]); continue; end…end

We avoid exiting by catching the error

2. Getting which years to

draw

42

Drawing Multiple Plots –Return if Nothing Need to be Done

% end case: % if no year was entered we are doneif (isempty(years2draw)) disp('No year was entered, exiting.'); return;end% opening a new figure figure;

3. Draw the plot

43

Drawing Multiple Plots –For loop – Variables Naming

for i = 1:length(years2draw) % getting the data cur_year = years2draw(i); cur_year_prices = gasoline_prices(find(years == cur_year),:); % setting the current subplot subplot(length(years2draw),1,i); % drawing plot(1:12,cur_year_prices, 'r-x','LineWidth',2) xlabel('Month', 'FontSize', 14); ylabel('$/Gallon', 'FontSize', 14); title(['Monthly Gas Prices during:' num2str(cur_year)], 'FontSize', 16); set(gca,'XTick',1:12, 'XTicklabel', months); grid; axis tight; end

Variables naming:

i for index

cur_ for current (value is specific for this iteration)

3. Draw the plot

44

Summary Boolean logic

Relational and logical operators What is true and what is false

Flow control: if-else-end constructions Switch-case-end constructions for loops while loops Loops flow control:

break continue

try-catch return

First use of Matlab debugger

Weizmann 2010 © 45

Extra examples - Not shown in the tutorial

46

quote = ['To err is human - and to blame' … 'it on a computer is even more so. '];Sub_str1 = 'i am';Sub_str2 = 'i';

quote == sub_str1

quote == sub_str2

strcmp(quote, sub_str1)

Strings are char arrays: Should have equal sizes Scalar expansion

String comparison – strcmp strncmp strcmpi (“i” - not case sensitive)

??? Error using ==> eqMatrix dimensions must agree.

Boolean Logic Tips and Pitfalls

[ 0 0 0 … 1 0 0 1 … 0 0]

0

47

Examples Which are similar? 1 || 2 && 0 1 || (2 && 0)(1 || 2) && 0Notice the Precedence

TrueOrFalse.m

Arrays - Which are similar?[][0, 1][1, 1]any([0, 1])all([0, 1])

48

Use Logical Expressions for Array Indexing

>> isnan([1, NaN])[0, 1]

>> v = 1:10;% Find all elements of v % that are product of 3 or equal 5% (hint – use mod(v,3)):>>>> find(v == 5 | mod(v,3) == 0)

[3, 5, 6, 9]