Control Statementsfaculty.citadel.edu/potisuk/elec206/ppt/ctrlflow.pdf · Control Statements ELEC...
Transcript of Control Statementsfaculty.citadel.edu/potisuk/elec206/ppt/ctrlflow.pdf · Control Statements ELEC...
1
1
Control Statements
ELEC 206
Prof. Siripong Potisuk
Objectives
Learn how to change the flow of execution of a
MATLAB program through some kind of a
decision-making process within that program
The program makes these decisions by comparing
values of some variables
The comparison is done by using a combination of
relational & logical operators
2
2
3
Controlling Flow of Execution
Constructs that allow MATLAB to decide whether
or not to execute some code that follows the
statement or to repeat certain groups of statements
Repetitions or loops:
1) for-end 2) while-end
Decision-making:
1) if-end 2) if-else-end
3) if-elseif-else-end 4) Switch case
Jumping or Skipping:
1) break 2) continue
Flow Chart
A diagram that shows the step-by-step flow of
execution.
It is particularly useful for showing how control
statements work.
Some common flowchart symbols are
represents a sequence of commands
represents an if-statement
shows the direction of code execution4
3
Repetitions or Loops
A loop executes one set of commands repeatedly.
MATLAB has two ways to control number of
times loop executes commands
- Method 1: for..end loop
executes commands a specified number of times
- Method 2: while..end loop
executes commands as long as a specified
expression is true
5
6
Loop index variable can have any variable name (usually
i, j, k, m, and n are used)
Avoid using i and j when working with complex numbers.
In general, loop body should not change value of k
Each for command must have an end command
4
7
1. The loop sets k to f, and executes the loop body, i.e.,
commands between the for and the end commands,
2. The loop then sets k to f+s and re-executes the body
3. The process repeats itself until k>t,at which point
the program continues with commands that follow the end command
8
f and t are usually integers while s usually omitted.
If omitted, loop uses an increment of 1
The increment s can be negative
e.g., k=25:–5:10
produces four passes with k = 25, 20, 15, 10
If f=t, the loop executes once
If f>t and s>0, or if f<t and s<0,loop not
executed
Value of k not displayed automatically. To display
the value in each pass, type k as one of commands in
loop body (sometimes useful for debugging)
When loop ends, k has the value last assigned to it
5
9
If k, s, and t are such that the last value of k
cannot be equal to t, then
- for s positive, the last pass is one where k has
largest value smaller than t.
For example, k=8:10:50
produces five passes (k = 8,18,28,38,48)
- for s negative, last pass is one where k has
smallest value larger than t
k can also be assigned specific values (typed as
a row vector)For example: for k = [7 9 –1 3 3 5]
10
EXAMPLE: Show the output of the following script
for k=1:3:10
k
x = k^2
end
fprintf('After loop k = %d\n', k);
Output: k = 1
x = 1
k = 4
x = 16
k = 7
x = 49
k = 10
x = 100
After loop k = 10
6
11
EXAMPLE: Write a script file using a for-end loop
to calculate the sum of the first n terms of the series:
for n = 4 and 20.
n = input(‘Enter the # of terms: ’)
sum = 0;
for k=1:n
sum = sum+(-1)^k*k/2^k;
end
fprintf(‘The total sum is %f \n', sum)
Output: Enter the # of terms: 4
The total sum is -0.125000
n
kk
k k
1 2
(-1)
12
The while-end loop used when- number of loop iterations not known
- a testable condition to stop looping when it is false.
Examples of test condition:- keep reading data from a file until the end is reached
- keep adding terms to a sum until the difference of the
last two terms is less than a certain amount
7
13
1. Loop starts by evaluating conditional expression
2. If true, executes code in the loop body, then goes
back to step 1
3. If false, skips code in the loop body and continue program execution with the code after the end
statement
14
The conditional expression must have a variable
which changes its value after each pass
There must be some value of the variable that
makes the conditional expression false
EXAMPLE: The script x = 1
while x <= 15
x = 2*x
end
outputs x = 1
x = 2
x = 4
x = 8
x = 16
8
15
EXAMPLE: The sequence of Fibonacci numbers F [n] is a
sequence of integers starting with 0 and 1, i.e., F [1] = 0 and
F [2] = 1. The next number in the sequence is the sum of the
previous two numbers, i.e., 0 1 1 2 3 5, 8, 13, …..
(a) Derive a recursive equation that can be used to compute
the sequence.
(b) Write a script file using a while-end loop to compute the
first 25 numbers in the sequence.
16
(a) F[n] = F [n 1] + F [n 2], n 3
(b) N = input(‘Enter the # of terms: ’)
F(1) = 0; F(2) = 1;
k = 3;
while k <= N
F(k) = F(k-1)+F(k-2);
k = k+1;
end
fprintf(‘The first %d terms of the
Fibonacci sequence is \n',N)
fprintf(‘%d \n’, F)
9
17
Output:Enter the # of terms: 25
The first 25 terms of the Fibonacci
sequence is
0 1 1 2 3
5 8 13 21 34
55 89 144 233 377
610 987 1597 2584 4181
6765 10946 17711 28657 46368
18
An infinite loop (also known as indefinite
loop) happens if the conditional expression
never becomes false, the loop will keep
executing... forever!
If there is no output from the loop (as if often
the case), it will look like MATLAB has
stopped responding
If your program gets caught in an indefinite
loop, activate (i.e., put the cursor in) the
Command Window and press CTRL+C
10
Common Causes of Indefinite Loops
1. No variable in conditional expression
d1 = 1; d2 = 10; d3 = 0;
while d1 < d2
fprintf('Distance = %d\n', d3);
end
2. Variable in conditional expression never changes
min_D = 42; D_Increment = 0;
D = 0;
while D < min_D
D = D + D_Increment;
end
19
d1 and d2 never change
Typo – should be 10
20
3. Wrong variable in conditional expression changed
min_D = 42; delta = 10;
D = 0;
while D < min_D
min_D = min_D + delta;
end
4. Conditional expression never becomes false
Min_D = 42; x = 0; y = 0;
while -sqrt(x^2+y^2) < min_D
x = x + 1;
y = y + x;
end
Typo – should be D
Typo – shouldn't be any negative
sign in front of sqrt
11
Conditional Statements
A construct that allows MATLAB to decide
whether or not to execute some code that follows
the statement
Four general forms
– if-end
– if-else-end
– if-elseif-else-end
– switch case
21
22
Conditional expression true MATLAB execute code segment between the if and end statement
conditional expression false MATLAB skips the code segment between the if and end statement
Then, it continues executing the code after the end-line
12
23
This construct executes one section of code if a
condition is true and a different section of code if
it is false.
24
13
25
if-elseif-else-end structure chooses
one of three or more sections of code to execute
Can have as many elseif statements as
necessary
Can omit else statement
If omitted and no match to if- or elseif-
statements, no code in structure gets executed
An easier-to-read alternative structure to theif-elseif-else-end structure
Choose code to execute based on value of scalar
or string, not just true/false
26
14
The switch-case structure
When the switch-expression is evaluated,
– If value is equal to value1, executes Group 1
commands then executes code after end
statement
– If value is equal to value2, same as above
but Group 2 commands only
– Etc.
27
The switch-case structure
If switch-expression not equal to any of values in case statement, commands after otherwise
executed.
If otherwise not present, no commands
executed
If switch expression matches more than one case value, only first matching case executed
Comparisons of text strings (within single quotes)
are case-sensitive.
28
15
Nesting
29
If a loop or conditional statement is placed inside
another loop or conditional statement, the former
are said to be nested in the latter
Most common to hear of a nested loop, i.e., a loop
within a loop
– Often occur when working with two-
dimensional problems
Each loop and conditional statement must have an end statement
30
16
The break Command
When inside a loop (for and while), break
terminates execution of loop
- MATLAB jumps from break to end
command of loop, then continues with next command (does not go back to the for or
while command of that loop).
- break ends whole loop, not just last pass
If break inside nested loop, only nested loop
terminated (not any outer loops)
31
The break Command
break command in script or function file but
not in a loop terminates execution of file
break command usually used within a
conditional statement.
If in loops, it provides way to end looping if
some condition is met
32
17
33
while( 1 )
name = input( 'Type name or q to quit:
', 's' );
if length(name) == 1 && name(1) == 'q'
break;
else
fprintf('Your name is %s\n', name);
end
end
Only way to exit loop!
Trick – "1" is always true so it makes loop iterate forever!
If user entered only one letter and it is a "q",
jump out of loop; Otherwise print name
The continue command
Use continue inside a loop (for- and while-) to
stop current iteration and start next iteration
continue usually part of a conditional statement
When MATLAB reaches continue it does not
execute remaining commands in loop but skips to the end command of loop and then starts a new
iteration
34
18
35
for ii=1:100
if rem( ii, 8 ) == 0
count = 0;
fprintf('ii=%d\n',ii);
continue;
end
% code
% more code
end
Every eight iteration reset count to zero, print the
iteration number, and skip
the remaining computations
in the loop