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

3 Why Loops? In Chapter 4 you learned a number of powerful MATLAB features for processing arrays In Chapter 4 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 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

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

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

13 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); 13

14 1) Finding the min…application 1) create a for loop with t going 0:0.01:4 2) calculate scalar x and y for each t 3) calculate distance, check for min, and save index of min inside loop 4) then show minT and minD

15 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

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

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

18 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

19 Homework #2 Ulam Sequence The Ulam Sequence The Ulam Sequence A mathematician named Ulam proposed generating a sequence of numbers from any positive integer n (n > 0) as follows: If n is 1, stop. If n is even, the next number is n/2. If n is odd, the next number is 3*n + 1. Continue with this process until reaching 1. Here are some examples for the first few integers. 2 -> 1 2 -> 1 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 4 -> 2 -> 1 4 -> 2 -> 1 5 -> 16 -> 8 -> 4 -> 2 -> 1 5 -> 16 -> 8 -> 4 -> 2 -> 1

20 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

21 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

22 Using Nested Loops

23 3) An optimization problem we need a way to check all possibilities Problem simplified from text

24 Hints for # 3 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???

25 Hints for #3, 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


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