Ch04b

advertisement

PowerPoint to accompany

Introduction to MATLAB 7 for Engineers

William J. Palm III

Chapter 4B

Programming LOOPS with MATLAB

Copyright © 2005. The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Agenda

For Loops and Common Tasks

Finding the max using a For loop

Nested For Loops

While Loops

Why Loops?

 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

 How does this work? A built in loop visits each cell

 These are great time-saving features

 Some problems are more complex and require explicitly writing our own loops to solve them

The “old fashioned” way programmers used to work

 More flexibility (and sometimes clarity) in formulating solutions

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

Flowchart of a for

Loop .

Figure 4.5–1

4-52

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

Common Tasks:

Making an Array

 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 end plot(x,y);

 Same as: x=[1:10]; y=x.^2; plot(x,y)

Q: What values are in y?

a) for k = 1:10 y(k)= k*10; end b) for k = 1:11 y(k)= 11 – k; end c) for k = 1:5 y(k)= k*10-100; end d) for k = 1:11 y(k)= (k-1)*0.2; end

Common Tasks:

Accessing an Array

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

Common Task:

Finding the Maximum

 The easy way:

[max, n] = max(hours)

 The hard(er) way:

 We can also do this using a loop

 With or without a vector

 Again, we get more flexibility for certain calculations

Finding the max…core idea

max=0; // make a variable to hold max num=input(‘enter a number’);

Core idea

Compare num with max… if num>max max=num; end

11

Finding the max…put in a loop

max=0; index=0; for i=1:5 num=input(‘enter a number’); if num > max max = num; end end max

12

max=0;

Finding the max…of a vector

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

13

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

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

4-57

The results displayed by the disp statement are 5, 9, and

17.

4-58

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.

More? See pages 221-223.

Flowchart of the while loop.

Figure 4.5–3

4-59

4-60

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.

Homework #2 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

3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1

4 -> 2 -> 1

5 -> 16 -> 8 -> 4 -> 2 -> 1

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

Tracing a Loop (example)

n = 1; y=20; sum = 0; while (n <= y) sum = sum + n*y; end n = n + 2; y = y/2;

Sum

0

2

32

57 done

3

5 n

1

7 y

20

10

5

2.5

Using Nested Loops

3) An optimization problem

we need a way to check all possibilities

Problem simplified from text

Hints for # 3

 The range of possible TVs: 0 to 300

(why? – check inventory)

 Range of possible speakers?

 Lots of permutations!

 If we have a vector p = [ numTV numSpkr];

 And a vector unit_cost=[ 80 40];

 Then profit = unit_cost*p';

 Q: How do we cover all permutations???

Hints for #3, continued

 A: Nested For Loops for numTV = 1:300 for numSpkr = 1: ??

p = [ numTV numSpkr] profit = … etc… also, check sufficient inventory for p end end

Download