Вы находитесь на странице: 1из 52

Chapter-5-6

Logical 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?

Flow chart of an if/else


structure
True

Block of code to
excute if the
comparison is true

Comparison

False

Block of code to
excute if the
comparison is false

Use an if structure to calculate a


natural log

Check to see if the input is positive


If

it is, calculate the natural log


If it isnt, 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

True

Sorry
Youll have
to wait

elseif
age<18

True

You may
have a youth
license

elseif
age<70
else
Drivers over 70
require a
special license

End

True

You may have a


standard license

Always test your


programs making
sure that youve
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.

The structure of switch/case


switch variable
case option1
code to be executed if variable is exactly
equal to option 1
case option2
code to be executed if variable is exactly
equal to option 2

case option_n
code to be executed if variable is exactly
equal to option n
otherwise
code to be executed if variable is not
equal to any of the options
end

Suppose you want to determine what


the airfare is to one of three cities

RememberYou 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 cant accidentally enter a bad choice
This means you dont need the otherwise
portion of the switch/case structure

Note that the otherwise portion of the


switch/case structure wasnt 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


as
sequences
selection

structures
repetition 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
~
xor

not
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.
if
else
elseif

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 structures
If comparison
statements
End
if G<50
disp(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 statement
day = 1
if 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 variable
case option 1
code to be executed if variable equal to option 1
case option 2
code executed if variable equal to option 2
Otherwise
If none of the option
end

For loop
% To understand For Loop
% For loop will do iterations only the fixed number of times
clc
clear
SumNumbers =0 ;
for I = 1:10
SumNumbers = SumNumbers+ I
end

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:5
a(k)=k^2
end

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.
clc
clear
Number =50
while Number > 20
Number = Number -5
end

Some Useful MATLAB commands

what
dir
ls
type test
delete test
cd a:
chdir a:
pwd
which test

List all m-files in current directory


List all files in current directory
Same as dir
Display test.m in command window
Delete test.m
Change directory to a:
Same as cd
Show current directory
Display directory path to closest test.m

MATLAB Logical Operators

MATLAB supports three logical operators.


not
and
or

~
&
|

% highest precedence
% equal precedence with or
% 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 = 1:100
disp X
end

for x = array

A while loop in MATLAB


while expression
while x <= 10
% execute these commands
end

Вам также может понравиться