chapter-6 logical functions.ppt
TRANSCRIPT
Chapter-5-6Logical functions, Selection structures and Repetition
structures
Faculty of Chemical & Natural Resources Engineering
Content
Flow diagram while loop and for loop. Addition, subtraction and other mathematical
functions. Break and continue statement. Branches if else, switch/case. Debugging tools
Execution Control
This chapter discusses techniques for changing the flow of control of a program, which may be necessary for two reasons.
You may want to execute some parts of the code under certain circumstances only.
You may want to repeat a section of code a certain number of times.
Logical functions A sequence is a list of commands that are
executed one after another. A selection structure allows the programmer
to execute one command if some criterion is true and second if the criterion is false.
A repetition structure, or loop, causes a group of statements to be executed multiple times.
Structures
Sequence Selection Repetition
Sequence Selection Repetition (Loop)
The if/else structure
The simple if triggers the execution of a block of code if a condition is true.
If it is false that block of code is skipped, and the program continues without doing anything.
What if instead you want to execute an alternate set of code if the condition is false?
Block of code to excute if the
comparison is true
ComparisonTrue False
Block of code to excute if the
comparison is false
Flow chart of an if/else structure
Use an if structure to calculate a natural log Check to see if the input is positive
If it is, calculate the natural logIf it isn’t, send an error message to the screen
M-file Program
Interactions in the Command Window
The if/else/elseif structure
Use the elseif for multiple selection criteria For example
Write a program to determine if an applicant is eligible to drive
Start
if age<16 TrueSorry – You’ll have to wait
age<18You may have a youth license
age<70
True
You may have a standard license
True
Drivers over 70 require a special license
End
elseif
elseif
else
Always test your programs – making sure that you’ve covered all the possible calculational paths
As a general rule…
If structures work well for scalars For vectors or arrays use a find function or.. Combine if structures with a repetition
structure Repetition structures are introduced in the next
chapter
switch/case
This structure is an alternative to the if/else/elseif structure
The code is generally easier to read This structure allows you to choose between multiple
outcomes, based on some criterion, which must be exactly true
When to use switch/case
The criterion can be either a scalar (a number) or a string.
In practice, it is used more with strings than with numbers.
switch variablecase option1
code to be executed if variable is exactly equal to option 1
case option2code to be executed if variable is exactly
equal to option 2…
case option_ncode to be executed if variable is exactly equal to option n
otherwisecode to be executed if variable is not equal to any of the options
end
The structure of switch/case
Suppose you want to determine what the airfare is to one of three cities
Remember…You tell the input command to expect a string by adding ‘s’ in the second field.
Menu
The menu function is often used in conjunction with a switch/case structure.
This function causes a menu box to appear on the screen with a series of buttons defined by the programmer.
input = menu(‘Message to the user’,’text for button 1’,’text for button 2’, etc)
Because the input is controlled by a menu box, the user can’t accidentally enter a bad choice
This means you don’t need the otherwise portion of the switch/case structure
Note that the otherwise portion of the switch/case structure wasn’t used
When you run this code a menu box appears
Instead of entering your choice from the command window, you select one of the buttons from the menu
If I select Honolulu…
Summary
Sections of computer code can be categorized assequencesselection structuresrepetition structures
Summary – Sequence
Sequences are lists of instructions that are executed in order
Summary – Selection Structure
Selection structures allow the programmer to define criteria (conditional statements) which the program uses to choose execution paths
Summary – Repetition Structures
Repetition structures define loops where a sequence of instructions is repeated until some criterion is met (also defined by conditional statements).
Summary – Relational Operators
MATLAB uses the standard mathematical relational operators<<=>>===~=
Recall that = is the assignment operator, and can not be used for comparisons
Summary – Logical Operators
MATLAB uses the standard logical operators && and || or~ notxor exclusive or
Summary – if family
The family of if structures allows the programmer to identify alternate computing paths dependent upon the results of conditional statements. ifelseelseif
Summary switch/case
Similar to the if/elseif/else structure Commonly used with menu
X=5 Y=1 X<Y another example X=[1, 2, 3, 4,5] Y=[-2,0,2,4,6] Use same sign
Selection structuresIf comparison statementsEndif G<50disp(‘G is a small value equal to :’)disp(G);end
if /elseif/ else The elseif function allows you to check
multiple criteria while keeping the code easy to read.
eg
Example for “If”, command% example for if statementday = 1if day== 7 % saturday state = 'weekend'elseif day ==1 % sunday state = 'weekend'else state= 'weekday'end
Switch and Case The above structure is often used when a series of programming
path options exists for a given variable, depending on its value. The above structure can be used either a scalar ( a number) or a
string.switch variablecase option 1 code to be executed if variable equal to option 1case option 2 code executed if variable equal to option 2OtherwiseIf none of the optionend
For loop
% To understand For Loop% For loop will do iterations only the fixed number of timesclcclear SumNumbers =0 ;for I = 1:10 SumNumbers = SumNumbers+ Iend
Exercise
Convert the values from degree to radian from 10 degree to 360 degree with an increment of 10.
Develop the table for the results. Formula for Radian = (Value in Degree X Pi)/180
Example for loop
for k= 1:5a(k)=k^2end
while loop% To understand while loop% while loop is an iteration loop% It will keep on going round and round until the condition is satisfied.% This loop is used, when we dont know the exact number of iterations.
clcclearNumber =50 while Number > 20 Number = Number -5 end
Some Useful MATLAB commands what List all m-files in current directory dir List all files in current directory ls Same as dir type test Display test.m in command window delete test Delete test.m cd a: Change directory to a: chdir a: Same as cd pwd Show current directory which test Display directory path to ‘closest’
test.m
MATLAB Logical Operators
MATLAB supports three logical operators.
not ~ % highest precedenceand & % equal precedence with oror | % equal precedence with and
break and continue
break causes the loop to terminate prematurely
continue causes MATLAB to skip a pass through the loop, but continue on until the criteria for ending is met
both are used in conjunction with an if statement
This program prompts the user 10 times to enter a value, and computes the natural log.
If a negative value is entered, the break command causes MATLAB to exit the loop
Notice that n had a value of 3 when the program terminated – if it had run to completion it would have had a value of 10
The continue command is similar to break, however instead of terminating the loop, the program just skips to the next pass.
Matlab Selection Structures An if - elseif - else structure in MATLAB. Note that elseif is one word.
if expression1 % is true% execute these commands
elseif expression2 % is true% execute these commands
else % the default% execute these commands
end
MATLAB Repetition Structures
A for loop in MATLAB for x = array for X = 1:100 disp X
end
A while loop in MATLAB while expression while x <= 10
% execute these commands end