1 / 46

AN ENGINEER’S GUIDE TO MATLAB 3rd Edition CHAPTER 4 PROGRAM FLOW CONTROL

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.

Télécharger la présentation

AN ENGINEER’S GUIDE TO MATLAB 3rd Edition CHAPTER 4 PROGRAM FLOW CONTROL

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. AN ENGINEER’S GUIDE TO MATLAB 3rd Edition CHAPTER 4 PROGRAM FLOW CONTROL

  2. 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.

  3. 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

  4. Program Control • Achieved by four program flow control structures – • while,if,for, andswitch • 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.

  5. 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.

  6. Relational and Logical Operators

  7. 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.

  8. 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.

  9. If we let • a = 1, b = 2 • f(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

  10. r = • 0 1 1 1 • p = • 1 1 1 0 • logi = • 0 1 1 0 • gofx = • 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.

  11. 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))

  12. This logical operator can be used to create the unit step function u(t), which is defined as • 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

  13. 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 1 • e = • 0 1 1 1 0

  14. Control of Program Flow • ifStatement • 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 #1 • elseif condition #2 % (optional) • expressions #2 • else% (optional) • expressions #3 • end

  15. Executed only when j = 1. This if statement encountered only when j = 1. These statements executed only when j = 1 and nnum 4. These statements executed only when j = 1 and nnum > 4. These statements executed only when j 1. • Example – • if j == 1 • z = sin(x) ; • if nnum <= 4 • nr = 1 ; • nc = 1; • else • nr = 1 ; • nc = 2; • end • else • nr = 2; • nc = 1; • end

  16. Note: When comparing a vector to a scalar, the condition is satisfied only when each element in the vector satisfies the condition.

  17. SwitchStatement - • 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_expression • case case_expression #1 • statements #1 • case case_expression #2 • statements #2 • case case_expression #n • statements #n • otherwise • statements #n+1 • end

  18. 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

  19. forLoop • A for loop repeats a series of statements a specific number of times. Its general form is • for variable = expression • statements • end • where one or more of the statements can be a function of variable.

  20. Array Pre-allocation – • Consider a single for loop of the form • A = zeros(Nrow, 1); % Array pre-allocation • for 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.

  21. 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 • end • end • where Nrow and Ncol are positive integers that previously have been assigned numerical values.

  22. 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 = N • a21 = N+1 and a2n = 2N • … • aN1 = (N1)N +1 and aNN = N 2 • The script is

  23. 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; • end • disp(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

  24. 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

  25. 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') end M = zeros(rA, cA); for c = 1:cA for r = 1:rA M(r, c) = A(r, c)*B(r, c); end end disp(M)

  26. Upon execution, we obtain 64 3 24 3 25 63 24 63 4

  27. 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 . where We shall determine the maximum value of Yj, j = 1, 2, 3, when we take 1000 values of  in the range 0  3.5.

  28. 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'; end for 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

  29. Upon execution, we obtain • Max of Y(1) = 1731.45 at Omega = 0.1682 • Max of Y(2) = 921.09 at Omega = 0.1682 • Max of Y(3) = 532.522 at Omega = 2.971

  30. 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 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.

  31. If b0 = L, then • where • in is the portion of pmonthat 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

  32. 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-allocation • prins = ints; % Pre-allocation • bals = ints; % Pre-allocation • pmon = (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); • end • disp(['Total interest = ', num2str(sum(ints),8)])

  33. Execution of the script gives • Enter loan amount: 100000 • Enter term of loan in months: 360 • Enter annual interest rate: 8 • Total interest = $164155.25 • The first three lines were answered by the user, the last line is the result.

  34. Example - Specification of the Elements of an Array • We shall create an (n×n) matrix whose elements are either +1 or 1 such that The script is

  35. 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; end end disp(M)

  36. 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.

  37. 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; • end • disp(H) • The execution of the script gives • -14 -6 0 12 12 17

  38. whileLoop • 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 • statements • end • where the expression defining condition is usually composed of one or more of the variables evaluated by statements.

  39. Example - Approximation to  • The following expression converges to 1/ when • and yo = 1/2 where We shall show that the difference |1/y4| is less than 1015. The script is

  40. xo = 1/sqrt(2); yo = 1/2; n = 0; • whileabs(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; • end • fprintf(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

  41. 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

  42. 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; end disp(route) f(x) = cos(ax)  0 0.5000 1.5000 2.5000 3.5000 4.5000

  43. Example – Convergence of a Series • Determine and display the number of terms that it takes for the series to converge to within 0.01% of its exact value, which is S = 2/6.

  44. series = 1; k = 2; exact = pi^2/6; • whileabs((series-exact)/exact) >= 1e-4 • series = series+1/k^2; • k = k+1; • end • disp(['Number of terms = ' num2str(k-1)]) • which, upon execution, displays to the command window • Number of terms = 6079

  45. Early Termination of Either afororwhileLoop • 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.

  46. When n < 0 the while loop is exited and the script continues from the next statement after this endstatement • Example – • for j = 1:14 • … • b = 1 • while b < 25 • … • if n < 0 • break • end • … • end • … • end

More Related