View
51
Download
3
Category
Preview:
DESCRIPTION
AN ENGINEER’S GUIDE TO MATLAB 3rd Edition CHAPTER 4 PROGRAM FLOW CONTROL. Chapter 4 – Objective Introduce various means of controlling the order in which a program’s expressions get evaluated and a set of relational and logical operators that are used to accomplish this control. Topics. - PowerPoint PPT Presentation
Citation preview
Copyright © Edward B. Magrab 2009
Chapter 4
1
An Engineer’s Guide to MATLAB
AN ENGINEER’S GUIDE TO MATLAB
3rd Edition
CHAPTER 4
PROGRAM FLOW CONTROL
Copyright © Edward B. Magrab 2009
Chapter 4
2
An Engineer’s Guide to MATLAB
Chapter 4 – Objective
Introduce various means of controlling the order in which a program’s expressions get evaluated and a set of relational and logical operators that are used to accomplish this control.
Copyright © Edward B. Magrab 2009
Chapter 4
3
An Engineer’s Guide to MATLAB
Topics
• Introduction – Logical Operators
• Control of Program Flow
Branching – if Statement
Branching – switch Statement
Specified repetition – for Loop
Unspecified repetition – while Loop
Early Termination of a for or while Loop
Copyright © Edward B. Magrab 2009
Chapter 4
4
An Engineer’s Guide to MATLAB
Program Control
• Achieved by four program flow control structures –
while, if, for, and switch
• Each time one of these statements appears, it must be followed at a later place within the program by an end statement.
• All expressions that appear between the control structure statement and the end statement are executed until all requirements of the structure are satisfied.
• Each of these control structure statements can appear as often as necessary within themselves or within other control structures.
When this occurs, they are called nested structures.
Copyright © Edward B. Magrab 2009
Chapter 4
5
An Engineer’s Guide to MATLAB
• Control structures frequently rely on relational and logical operators to determine whether a condition has been met.
• When a condition has been met, the structure directs the program to a specific part of the program to execute one or more expressions.
• One can use the relational and logical operators to create a logical function whose output is 1 if the relational and logical operations are true and 0 if they are false.
Copyright © Edward B. Magrab 2009
Chapter 4
6
An Engineer’s Guide to MATLAB
Relational and Logical Operators
Conditional
Mathematical symbol
MATLAB symbol
Relational operators equal not equal less than greater than less than or equal greater than or equal
Logical operators and or not
= < > AND OR NOT
== ~= < > <= >= & or && | or || ~
Copyright © Edward B. Magrab 2009
Chapter 4
7
An Engineer’s Guide to MATLAB
When using control structures –
• Indent the statements following each control structure definition up to, but not including, the end statement.
Greatly improves the readability.
• When the structures are nested, the entire nested structure is indented, with each nested structure’s indentation preserved.
• When using MATLAB's editor, the indenting can be done automatically.
Copyright © Edward B. Magrab 2009
Chapter 4
8
An Engineer’s Guide to MATLAB
Logical Operator –
Suppose that we want to create a function g(x) such that
g(x) = f(x) a x < b = 0 x < a and b x
The logical operator is formed by
y = (a<=x & x<b)
where a and b have been assigned numerical values prior to this statement and
(a<=x & x<b)
is the logical operator that has a value of 1 (true) when x a and x < b. Its value is 0 (false) for all other values of x.
Copyright © Edward B. Magrab 2009
Chapter 4
9
An Engineer’s Guide to MATLAB
If we let
a = 1, b = 2f(x) = ex/2, x = [4, 1, 1, 4]
then a script using the logical operator is
a = -1; b = 2;x = [-4, -1, 1, 4];r = (a <= x)p = (x < b)logi = (r & p)gofx = exp(x/2).*logi
which, upon execution, yields
Copyright © Edward B. Magrab 2009
Chapter 4
10
An Engineer’s Guide to MATLAB
r = 0 1 1 1p = 1 1 1 0logi = 0 1 1 0gofx = 0 0.6065 1.6487 0
where the intermediate expressions r, p, and logi were introduced to explicitly show that they are each a vector of logical results; ones (true) and zeros (false).
Notice that dot multiplication was employed because x and logi are each (1×4) vectors.
Copyright © Edward B. Magrab 2009
Chapter 4
11
An Engineer’s Guide to MATLAB
In practice, the expressions r, p, logi and gofx are combined into one expression as shown below.
a = -1; b = 2;x = [-4, -1, 1, 4];gofx = exp(x/2).*((a<=x) & (x<b))
Copyright © Edward B. Magrab 2009
Chapter 4
12
An Engineer’s Guide to MATLAB
This logical operator can be used to create the unit step function u(t), which is defined as
( ) = 1 0
= 0 < 0
u t t
t
If t varies by increments of 0.25 in the range 1 t 1, then the following script creates the unit step function
t = -1:0.25:1;UnitStep = (t>=0);disp(' t UnitStep')disp([t' UnitStep'])
t UnitStep -1.0000 0 -0.7500 0 -0.5000 0 -0.2500 0 0 1.0000 0.2500 1.0000 0.5000 1.0000 0.7500 1.0000 1.0000 1.0000
Copyright © Edward B. Magrab 2009
Chapter 4
13
An Engineer’s Guide to MATLAB
Example –
Compare two vectors of equal length. Then
a = [4, 5, 6, 7, 8]; b = [4, 3, 2, 1, 8];d = (a == b)e = (a > b)
Its execution gives
d = 1 0 0 0 1e = 0 1 1 1 0
Copyright © Edward B. Magrab 2009
Chapter 4
14
An Engineer’s Guide to MATLAB
Control of Program Flow
if Statement
The if statement is a conditional statement that branches to different parts of its structure depending on the satisfaction of certain conditional expressions.
The general form of the if statement is
if condition #1 expressions #1elseif condition #2 % (optional) expressions #2else % (optional) expressions #3end
Copyright © Edward B. Magrab 2009
Chapter 4
15
An Engineer’s Guide to MATLAB
Example –
if j == 1 z = sin(x) ; if nnum <= 4 nr = 1 ; nc = 1; else nr = 1 ; nc = 2; endelse nr = 2; nc = 1; end
These statements executed only when j = 1 and nnum 4.
These statements executed only when j 1.
Executed only when j = 1.
This if statement encountered only when j = 1.
These statements executed only when j = 1 and nnum > 4.
Copyright © Edward B. Magrab 2009
Chapter 4
16
An Engineer’s Guide to MATLAB
Note: When comparing a vector to a scalar, the condition is satisfied only when each element in the vector satisfies the condition.
Copyright © Edward B. Magrab 2009
Chapter 4
17
An Engineer’s Guide to MATLAB
Switch Statement -
The switch structure is, essentially, an alternative to using a series of if-elseif-else-end structures.
The general form of the switch statement is
switch switch_expressioncase case_expression #1
statements #1case case_expression #2
statements #2case case_expression #n
statements #notherwise
statements #n+1end
Copyright © Edward B. Magrab 2009
Chapter 4
18
An Engineer’s Guide to MATLAB
Example –
k = 3;switch k case 1 disp('Case 1') Executed only when k = 1
case {2, 3} Notice that cell is used
disp('Case 2 or 3' ) Executed only when k = 2, 3
case 9 disp('Case 9') Executed only when k = 9
otherwise disp('Otherwise') Executed only when k 1, 2, 3, or 9
end
Copyright © Edward B. Magrab 2009
Chapter 4
19
An Engineer’s Guide to MATLAB
for Loop
A for loop repeats a series of statements a specific number of times. Its general form is
for variable = expression statementsend
where one or more of the statements can be a function of variable.
Copyright © Edward B. Magrab 2009
Chapter 4
20
An Engineer’s Guide to MATLAB
Array Pre-allocation –
Consider a single for loop of the form
A = zeros(Nrow, 1); % Array pre-allocationfor r = 1:Nrow Statements A(r) = ...end
where Nrow is a positive integer that previously has been assigned a numerical value.
The addition of the array assignment statement
A = zeros(Nrow, 1);
ensures that the loop executes at maximum speed.
Copyright © Edward B. Magrab 2009
Chapter 4
21
An Engineer’s Guide to MATLAB
For nested for loops, we have that
B = zeros(Nrow, Ncol); % Array pre-allocation for c = 1:Ncol % Column must be outer loop index Statements for r = 1:Nrow % Row must be inner loop index Statements B(r, c) = ... % Index order must be as shown endend
where Nrow and Ncol are positive integers that previously have been assigned numerical values.
Copyright © Edward B. Magrab 2009
Chapter 4
22
An Engineer’s Guide to MATLAB
Example – Creation of a Sequentially-numbered Square Matrix
We shall generate an (N×N) matrix in which the elements of each row are such that
a11 = 1 and a1n = Na21 = N+1 and a2n = 2N…aN1 = (N 1)N +1 and aNN = N 2
The script is
Copyright © Edward B. Magrab 2009
Chapter 4
23
An Engineer’s Guide to MATLAB
N = input('Enter a positive integer < 15: ');Matr = zeros(N, N);for r = 1:N Matr(r,1:N) = ((r-1)*N+1):r*N;enddisp(Matr)
Upon execution, we obtain
Enter a positive integer < 15: 9 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
Copyright © Edward B. Magrab 2009
Chapter 4
24
An Engineer’s Guide to MATLAB
Example – Dot Multiplication of Matrices
We shall perform the dot multiplication of two matrices A and B of the same order.
The script is equivalent to A.*B.
In our case, we will illustrate the procedure using A = magic(3) and B = A'.
However, in general, before the multiplication can be performed, one must ensure that the order of the matrices is equal.
The script is
Copyright © Edward B. Magrab 2009
Chapter 4
25
An Engineer’s Guide to MATLAB
A = magic(3);B = A';[rA, cA] = size(A);[rB, cB] = size(B);if (rA~=rB)||(cA~=cB) error('Matrices must be the same size')endM = zeros(rA, cA);for c = 1:cA for r = 1:rA M(r, c) = A(r, c)*B(r, c); endenddisp(M)
Copyright © Edward B. Magrab 2009
Chapter 4
26
An Engineer’s Guide to MATLAB
Upon execution, we obtain
64 3 24 3 25 63 24 63 4
Copyright © Edward B. Magrab 2009
Chapter 4
27
An Engineer’s Guide to MATLAB
Example – Analysis of the Frequency Spectrum of a Three Degree-of-Freedom System
Consider the following solution to a three degree-of-freedom system as a function of the forcing frequency .
12Y I A B
where
1
2
3
14 27 14 4
8 14 8 2.5
2.5 4 2.5 1
Y
Y Y B A
Y
We shall determine the maximum value of Yj, j = 1, 2, 3, when we take 1000 values of in the range 0 3.5.
Copyright © Edward B. Magrab 2009
Chapter 4
28
An Engineer’s Guide to MATLAB
N = 1000;B = [14, 8, 2.5];A = [27, 14, 4; 14, 8, 2.5; 4, 2.5, 1];Om2 = linspace(0, 3.5, N).^2;sav = zeros(N, 3);for k = 1:N sav(k,:) = inv(eye(3)-Om2(k)*A)*B';endfor h = 1:3 [mx, ix] = max(sav(:,h)); disp(['Max of Y(' int2str(h) ') = ' num2str(mx, 6) ' at
Omega = ' num2str(sqrt(Om2(ix)), 4)])end
Copyright © Edward B. Magrab 2009
Chapter 4
29
An Engineer’s Guide to MATLAB
Upon execution, we obtain
Max of Y(1) = 1731.45 at Omega = 0.1682Max of Y(2) = 921.09 at Omega = 0.1682Max of Y(3) = 532.522 at Omega = 2.971
Copyright © Edward B. Magrab 2009
Chapter 4
30
An Engineer’s Guide to MATLAB
Example - Total Interest of a Loan
Compute the total interest on a loan when the amount of the loan is L, its duration is m months, and its annual percentage interest Ia. The monthly payment pmon is determined from
-1- (1+ )mon m
iLp
i
where i = Ia/1200 is the monthly interest rate expressed as a decimal number.
As the loan is being paid off, a portion of the payment is used to pay the interest, and the remainder is applied to the unpaid loan amount.
The unpaid loan amount after each payment is called the balance.
Copyright © Edward B. Magrab 2009
Chapter 4
31
An Engineer’s Guide to MATLAB
1,2,3n n-1
n mon n
n n-1 n
i = ib
P = p - i n = , ...,m
b = b - P
If b0 = L, then
where
in is the portion of pmon that goes towards the payment of the interest.
Pn is the portion of the payment that goes towards the reduction of the balance bn—that is, the amount required to pay off the loan.
The total interest paid at the end of the loan’s duration is
1
m
T jj
i i
Copyright © Edward B. Magrab 2009
Chapter 4
32
An Engineer’s Guide to MATLAB
The script to compute iT is
loan = input('Enter loan amount: ');durat = input('Enter term of loan in months: ');int = input('Enter annual interest rate: ')/1200;ints = zeros(durat,1); % Pre-allocationprins = ints; % Pre-allocationbals = ints; % Pre-allocationpmon = (loan*int)/(1-(1+int)^(-durat));bals(1) = loan;for m = 2:durat+1 ints(m) = int*bals(m-1); prins(m) = pmon-ints(m); bals(m) = bals(m-1)-prins(m);enddisp(['Total interest = ', num2str(sum(ints),8)])
-1- (1+ )mon m
iLp
i
n n-1
n mon n
n n-1 n
i = ib
P = p - i
b = b - P
Copyright © Edward B. Magrab 2009
Chapter 4
33
An Engineer’s Guide to MATLAB
Execution of the script gives
Enter loan amount: 100000Enter term of loan in months: 360Enter annual interest rate: 8Total interest = $164155.25
The first three lines were answered by the user, the last line is the result.
Copyright © Edward B. Magrab 2009
Chapter 4
34
An Engineer’s Guide to MATLAB
Example - Specification of the Elements of an Array
We shall create an (n×n) matrix whose elements are either +1 or 1 such that
1 1 1
1 1 1( )
1 1 1M n n
The script is
Copyright © Edward B. Magrab 2009
Chapter 4
35
An Engineer’s Guide to MATLAB
n = input('Enter the order of the square matrix: ');k = 1:n;M = zeros(n, n);OddRow = (-1).^(k-1);EvenRow = (-1).^k;for m = 1:2:n M(m,:) = OddRow; if m+1 <= n M(m+1,:) = EvenRow; endenddisp(M)
1 1 1
1 1 1
1 1 1M
Copyright © Edward B. Magrab 2009
Chapter 4
36
An Engineer’s Guide to MATLAB
The execution of this script for n = 3 displays to the command window
Enter the order of the square matrix: 3
1 -1 1 -1 1 -1 1 -1 1
where the value 3 was entered by the user.
Copyright © Edward B. Magrab 2009
Chapter 4
37
An Engineer’s Guide to MATLAB
Example - Sorting a Vector of Numerical Values in Ascending Order
We shall create a script that does the same thing sort.
H = [17, 12, 12, -6, 0, -14];LH = length(H);for k = 1:(LH-1) smin = H(k); for m = (k+1):LH if H(m) < smin smin = H(m); M = m; end end temp = H(k); H(k) = H(M); H(M) = temp;enddisp(H)
The execution of the script gives
-14 -6 0 12 12 17
Copyright © Edward B. Magrab 2009
Chapter 4
38
An Engineer’s Guide to MATLAB
while Loop
The while loop repeats one or more statements an indefinite number of times, leaving the loop only when a specified condition has been satisfied.
Its general form is
while condition statementsend
where the expression defining condition is usually composed of one or more of the variables evaluated by statements.
Copyright © Edward B. Magrab 2009
Chapter 4
39
An Engineer’s Guide to MATLAB
Example - Approximation to
The following expression converges to 1/ when and yo = 1/2 1 2ox
2 11 1 11 2 0,1,2,...n
n n n ny y x x n
where2
1 2
1 1
1 1
nn
n
xx
x
We shall show that the difference |1/ y4| is less
than 1015. The script is
Copyright © Edward B. Magrab 2009
Chapter 4
40
An Engineer’s Guide to MATLAB
xo = 1/sqrt(2); yo = 1/2; n = 0;while abs(1/pi - yo) > 1e-15 xo = (1-sqrt(1-xo^2))/(1+sqrt(1-xo^2)); yo = yo*(1+xo)^2-2^(n+1)*xo; n = n+1;endfprintf(1, 'For n = %2.f, |1/pi-y_(n+1)| = %5.4e\n', n-1,
abs(1/pi - yo))
Execution of this script results in
For n = 3, |1/pi-y_(n+1)| = 4.9960e-016
Copyright © Edward B. Magrab 2009
Chapter 4
41
An Engineer’s Guide to MATLAB
Example – Interval Halving and the Roots of Functions
Find a series of positive values of x (x1, x2, …) that make f(x) = 0, assuming that the sign of f(x) alternates as x increases
x
xstart + 5/2
/2
xstart + 11/4
f(x1) 0 f(x2) 0
f(x)
xstart + 2 xstart xstart +
f(x) > 0
f(x) < 0
/4
xstart + 3
Copyright © Edward B. Magrab 2009
Chapter 4
42
An Engineer’s Guide to MATLAB
n = 5; a = pi; increment = 0.3; tolerance = 1e-6; xstart = 0.2; x = xstart; dx = increment;for m = 1:n s1 = sign(cos(a*x)); while dx/x > tolerance if s1 ~= sign(cos(a*(x+dx))) dx = dx/2; else x = x+dx; end end route(m) = x; dx = increment; x = 1.05*x;enddisp(route)
f(x) = cos(ax) 0
0.5000 1.5000 2.5000 3.5000 4.5000
x
xstart + 5/2
/2
xstart + 11/4
f(x1) 0 f(x2) 0
f(x)
xstart + 2 xstart xstart +
f(x) > 0
f(x) < 0
/4
xstart + 3
Copyright © Edward B. Magrab 2009
Chapter 4
43
An Engineer’s Guide to MATLAB
Example – Convergence of a Series
Determine and display the number of terms that it takes for the series
2=1
1N
Nn
Sn
to converge to within 0.01% of its exact value, which is S = 2/6.
Copyright © Edward B. Magrab 2009
Chapter 4
44
An Engineer’s Guide to MATLAB
series = 1; k = 2; exact = pi^2/6;while abs((series-exact)/exact) >= 1e-4 series = series+1/k^2; k = k+1;enddisp(['Number of terms = ' num2str(k-1)])
which, upon execution, displays to the command window
Number of terms = 6079
2=1
1N
Nn
Sn
Copyright © Edward B. Magrab 2009
Chapter 4
45
An Engineer’s Guide to MATLAB
Early Termination of Either a for or while Loop
The break function is used to terminate either a for or while loop.
If the break function is within nested for or while loops, then it returns to the next higher level for or while loop.
Copyright © Edward B. Magrab 2009
Chapter 4
46
An Engineer’s Guide to MATLAB
Example –
for j = 1:14 … b = 1 while b < 25 … if n < 0 break end
… end …end
When n < 0 the while loop is exited and the script continues from the next statement after this end statement
Recommended