32p. Nested loops _printable_

# 32p. Nested loops _printable_ - Nested Loops For an...

This preview shows pages 1–2. Sign up to view the full content.

1 ©2009 by L. Lagerstrom Nested Loops • For an introduction to the basic concepts, see the associated video clip • Nested loop structure • Nested loop results • Nested loop execution • Nested loop example • Finding the location of the max value in an array • The indmax function ©2009 by L. Lagerstrom The Nested Loop Structure Often it's useful to put one loop inside another loop. We call this a double loop, or a nested loop. The basic structure is: for m = 1:3 for n = 1:4 fprintf('Value of m is %.0f and value of n is %.0f \n', m, n) end end See if you can figure out what will be displayed when this code is run. (We give the results on the next slide.) ©2009 by L. Lagerstrom Nested Loop Results Our nested loop example: for m = 1:3 for n = 1:4 fprintf('Value of m is %.0f and value of n is %.0f \n', m, n) end end The displayed results will be: Value of m is 1 and value of n is 1 Value of m is 1 and value of n is 2 Value of m is 1 and value of n is 3 Value of m is 1 and value of n is 4 Value of m is 2 and value of n is 1 Value of m is 2 and value of n is 2 Value of m is 2 and value of n is 3 [etc., etc.] Value of m is 3 and value of n is 4 ©2009 by L. Lagerstrom Nested Loop Execution From the loop code, and/or from the displayed results on the previous slide, we see that the loops execute as follows: 1. Matlab sets m to a value of 1 and starts the outer loop. 2. Once inside the outer loop, Matlab finds the inner loop. So it sets n to 1 and starts the inner loop. 3. The inner loop executes completely, meaning, in this case, that it iterates 4 times, displaying the "Value of. .." message each time. The value of the inner loop variable (n) changes each time, but the value of m (from the outer loop) does not. 4. When the inner loop is done, Matlab proceeds and finds that it is at the end of the first iteration of the outer loop. So it returns to the beginning of the outer loop, sets m to 2, and starts the next iteration. During this second iteration of the outside loop, the inner loop will

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 3

32p. Nested loops _printable_ - Nested Loops For an...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online