Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2005. The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.

Similar presentations


Presentation on theme: "Copyright © 2005. The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm."— Presentation transcript:

1 Copyright © 2005. The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm III Chapter 4B Programming LOOPS with MATLAB PowerPoint to accompany

2 Agenda For Loops and Common Tasks For Loops and Common Tasks Finding the max using a For loop Finding the max using a For loop Nested For Loops Nested For Loops While Loops While Loops Switch statement Switch statement

3 Why Loops? In Chapter 3 you learned a number of powerful MATLAB features for processing arrays In Chapter 3 you learned a number of powerful MATLAB features for processing arrays x(x>5) shows all x cells that are larger than 5 x(x>5) shows all x cells that are larger than 5 How does this work? A built in loop visits each cell How does this work? A built in loop visits each cell These are great time-saving features These are great time-saving features Some problems are more complex and require explicitly writing our own loops to solve them Some problems are more complex and require explicitly writing our own loops to solve them The “old fashioned” way programmers used to work The “old fashioned” way programmers used to work More flexibility (and sometimes clarity) in formulating solutions More flexibility (and sometimes clarity) in formulating solutions

4 for Loops A simple example of a for loop is for k = 5:10:35 x = k^2 end The loop variable k is initially assigned the value 5, and x is calculated from x = k^2. Each successive pass through the loop increments k by 10 and calculates x until k exceeds 35. Thus k takes on the values 5, 15, 25, and 35, and x takes on the values 25, 225, 625, and 1225. The program then continues to execute any statements following the end statement. 4-51

5 Flowchart of a for Loop. Figure 4.5–1 4-52

6 Note the following rules when using for loops with the loop variable expression k = m:s:n: The step value s may be negative. Example: k = 10:-2:4 produces k = 10, 8, 6, 4. If s is omitted, the step value defaults to 1. If s is positive, the loop will not be executed if m is greater than n. If s is negative, the loop will not be executed if m is less than n. If m equals n, the loop will be executed only once. If the step value s is not an integer, round-off errors can cause the loop to execute a different number of passes than intended. 4-53

7 Common Tasks: Making an Array Loops can create arrays for you: Loops can create arrays for you: for k = 1:10 x(k) = k;  cell #1 gets 1, #2 gets 2... y(k)= k^2;  k is a scalar so no '.' needed y(k)= k^2;  k is a scalar so no '.' neededendplot(x,y); Same as: x=[1:10]; y=x.^2; plot(x,y) Same as: x=[1:10]; y=x.^2; plot(x,y)

8 Q: What values are in y? d) for k = 1:11 y(k)= (k-1)*0.2; y(k)= (k-1)*0.2; end end b) for k = 1:11 y(k)= 11 – k; y(k)= 11 – k; end end a) for k = 1:10 y(k)= k*10; y(k)= k*10; end end c) for k = 1:5 y(k)= k*10-100; y(k)= k*10-100; end end

9 Common Tasks: Accessing an Array Loops can also sample data from the cells of a pre-existing array. Suppose: Loops can also sample data from the cells of a pre-existing array. Suppose: hours=[40, 65, 48, 30, 20]; hours=[40, 65, 48, 30, 20]; totalOvertime = 0; totalOvertime = 0; for k = 1:length(hours) for k = 1:length(hours) if hours(k) > 40 totalOvertime=totalOvertime + hours(k) - 40; totalOvertime=totalOvertime + hours(k) - 40; end endend totalOvertime (result is 33)

10 Easy… 1) create t and vs using vector notation 2) create VL using loop and if

11 Problem 24 continued

12 Common Task: Finding the Maximum The easy way: The easy way: [max, n] = max(hours) The hard(er) way: The hard(er) way: We can also do this using a loop We can also do this using a loop With or without a vector With or without a vector Again, we get more flexibility for certain calculations Again, we get more flexibility for certain calculations

13 Finding the max…core idea max=0; // make a variable to hold max num=input(‘enter a number’); Core idea Core idea Compare num with max… Compare num with max… if num>max max=num; max=num;end 13

14 Finding the max…put in a loop max=0; index=0; for i=1:5 for i=1:5 num=input(‘enter a number’); num=input(‘enter a number’); if num > max if num > max max = num; max = num; end end max max 14

15 Finding the max…of a vector max=0; hours=[40, 65, 48, 30, 20]; hours=[40, 65, 48, 30, 20]; for i=1:length(hours) for i=1:length(hours) if hours(i) > max if hours(i) > max max = hour(i); max = hour(i); max_cell = i;  capture cell number max_cell = i;  capture cell number end end disp('max = '); disp(max); disp('max = '); disp(max); disp(' at cell # '); disp(index); disp(' at cell # '); disp(index); 15

16 Finding the min…application 1) create t, x and y using vector notation 2) make a loop for k=1: length(t) 3) calculate distance, check for min, and save index of min inside loop 4) then show t(min) and minDist

17 Write a function, make a graph… this function only takes scalars

18 Problem 22 continued

19 MISCELLANEOUS The continue Statement The following code uses a continue statement to avoid computing the logarithm of a negative number. x = [10,1000,-10,100]; y = NaN*x; for k = 1:length(x) if x(k) < 0 continue end y(k) = log10(x(k)); end y The result is y = 1, 3, NaN, 2. 4-54More? See pages 210-217.

20 MISCELLANEOUS Use of a Mask We can often avoid the use of loops and branching and thus create simpler and faster programs by using a logical array as a mask that selects elements of another array. Any elements not selected will remain unchanged. The following session creates the logical array C from the numeric array A given previously. >>A = [0, -1, 4; 9, -14, 25; -34, 49, 64]; >>C = (A >= 0); The result is C = 1 0 1 0 1 14-55

21 We can use this mask technique to compute the square root of only those elements of A given in the previous program that are no less than 0 and add 50 to those elements that are negative. The program is A = [0, -1, 4; 9, -14, 25; -34, 49, 64]; C = (A >= 0); A(C) = sqrt(A(C)) A(~C) = A(~C) + 50 4-56More? See pages 217-218.

22 An optimization problem we need a way to check all possibilities Problem simplified from text

23 Hints for # 27 The range of possible TVs: 0 to 300 (why? – check inventory) The range of possible TVs: 0 to 300 (why? – check inventory) Range of possible speakers? Range of possible speakers? Lots of permutations! Lots of permutations! If we have a vector p = [ numTV numSpkr]; If we have a vector p = [ numTV numSpkr]; And a vector unit_cost=[ 80 40]; And a vector unit_cost=[ 80 40]; Then profit = unit_cost*p'; Then profit = unit_cost*p'; Q: How do we cover all permutations??? Q: How do we cover all permutations???

24 Hints for 27, continued A: Nested For Loops A: Nested For Loops for numTV = 1:300 for numSpkr = 1: ?? for numSpkr = 1: ?? p = [ numTV numSpkr] p = [ numTV numSpkr] profit = … etc… profit = … etc… also, check sufficient inventory for p end endend

25 while Loops The while loop is used when the looping process terminates because a specified condition is satisfied, and thus the number of passes is not known in advance. A simple example of a while loop is x = 5; while x < 25 disp(x) x = 2*x - 1; end The results displayed by the disp statement are 5, 9, and 17. 4-57

26 The typical structure of a while loop follows. while logical expression statements end For the while loop to function properly, the following two conditions must occur: 1.The loop variable must have a value before the while statement is executed. 2. The loop variable must be changed somehow by the statements. 4-58More? See pages 221-223.

27 Flowchart of the while loop. Figure 4.5–3 4-59

28 A simple example of a while loop is x = 5;k = 0; while x < 25 k = k + 1; y(k) = 3*x; x = 2*x-1; end The loop variable x is initially assigned the value 5, and it keeps this value until the statement x = 2*x - 1 is encountered the first time. Its value then changes to 9. Before each pass through the loop, x is checked to see if its value is less than 25. If so, the pass is made. If not, the loop is skipped. 4-60

29 Another Example of a while Loop Write a script file to determine how many terms are required for the sum of the series 5k 2 – 2k, k = 1, 2, 3, … to exceed 10,000. What is the sum for this many terms? total = 0;k = 0; while total < 1e+4 k = k + 1; total = 5*k^2 - 2*k + total; end disp(’The number of terms is:’) disp(k) disp(’The sum is:’) disp(total) The sum is 10,203 after 18 terms. 4-61

30 Tracing a Loop Hand tracing is a great way to debug a loop Make a table of all the variables Update table as program changes variables

31 Tracing a Loop (example) n = 1; y=20; sum = 0; while (n <= y) sum = sum + n*y; n = n + 2; y = y/2; end Sumny 0120 2310 3255 5772.5 done

32 Tracing (homework problem)

33 The Editor/Debugger containing two programs to be analyzed. Figure 4.7–1 4-65More? See pages 228-234.

34 The switch Structure The switch structure provides an alternative to using the if, elseif, and else commands. Anything programmed using switch can also be programmed using if structures. However, for some applications the switch structure is more readable than code using the if structure. 4-62

35 Syntax of the switch structure switch input expression (which can be a scalar or string). case value1 statement group 1 case value2 statement group 2. otherwise statement group n end 4-63

36 The following switch block displays the point on the compass that corresponds to that angle. switch angle case 45 disp(’Northeast’) case 135 disp(’Southeast’) case 225 disp(’Southwest’) case 315 disp(’Northwest’) otherwise disp(’Direction Unknown’) end 4-64More? See pages 225-227.

37 How to input type of materials? Introducing…text variables!

38 This uses your leap year function This uses your leap year function (prob18 from assignment 4) For example input 3 2 2009 For example input 3 2 2009 it says this is day number 61 it says this is day number 61 (31 for Jan + 28 for Feb + 2 for Mar) (31 for Jan + 28 for Feb + 2 for Mar) for dates > Feb 28 you have to add leapYear return value (0 for no LY or 1 for leap year)


Download ppt "Copyright © 2005. The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm."

Similar presentations


Ads by Google