ECE 1331 MATLAB: Iteration - PowerPoint PPT Presentation

1 / 52
About This Presentation
Title:

ECE 1331 MATLAB: Iteration

Description:

Examples: Display the square roots of the odd integers from 1 to 9 % explicit for loop ... outer loop body resumes. outer loop cleanup. This is the inner loop. ... – PowerPoint PPT presentation

Number of Views:111
Avg rating:3.0/5.0
Slides: 53
Provided by: dianadela
Category:

less

Transcript and Presenter's Notes

Title: ECE 1331 MATLAB: Iteration


1
ECE 1331MATLAB Iteration
  • Loops and Implied Loops

2
Loops and Implied Loops
  • A loop is a structure for repeating a sequence of
    instructions a number of times. Each repetition
    is called a pass. Looping is also also called
    iteration.

3
Loops and Implied Loops
  • "iterate"
  • to perform again repeat
  • Consider the following problem
  • given vector of numbers named data
  • want to add up values in data greater than some
    scalar named val
  • must "iterate" through values in data, comparing
    each one to val, then summing those values
    greater than val
  • This is a "loop" operation, as indicated by the
    pseudocode
  • initialize total to zero
  • for each value in data
  • if value is greater than val,
  • add value to total

4
Loops and Implied Loops
5
Iteration in Spreadsheets
  • Iteration in spreadsheets takes place when a
    formula operating on a value in a column is
    copied down so that it similarly operates on the
    entire column of data.
  • For example
  • the problem is solved in Excel as shown to the
    right
  • Assume that cell C1 is named "val"
  • Look closely and see how this is an
    implementation of the flowchart and pseudocode.

6
Implied Loops in MATLAB
  • Iteration takes place "automatically" in MATLAB
    because of the built-in vector operations. We
    call this an implied loop.
  • Since data is a vector, the operation data gt val
    causes automatic iteration
  • comparing val to each element of data, in turn
  • automatic iteration also takes place when data is
    given a logical subscript (as shown on the right)
  • But look carefully and see, again, that this is
    an implementation of the flowchart
  • data 3,4,1,-3,8,6,-5,11
  • val 5
  • Solution in several explicit steps
  • subscripts of values gt val
  • indices find(datagtval)
  • actual values gt val
  • bigdata data(indices)
  • sum of those values
  • total sum(bigdata)
  • Solution in fewer steps
  • sum data values gt val
  • total sum(data(datagtval))

7
for Loops
8
for Loops
  • The for loops in MATLAB (or any other language)
    are a way of explicitly implementing a loop
    structure for iteration. This is more tedious
    than MATLAB's implied loops, but is also more
    flexible.

9
for Loop Structure 1
  • One structure of a for loop is
  • for loop-variable msn
  • statements
  • end
  • where msn is the usual expression for
    generating elements of a vector
  • m initial value
  • s step or increment
  • n terminating value
  • The loop-variable takes on each of the vector
    values for one pass through the loop, executing
    the statements once during each pass.

10
for Loop Structure 2
  • Another structure is
  • for loop-variable aVector
  • statements
  • end
  • In the second form above, aVector can already
    have a set of values
  • The loop-variable takes on each of the vector
    values for one pass through the loop, executing
    the statements once during each pass.

11
Examples
  • Display the square roots of the odd integers from
    1 to 9
  • explicit for loop
  • for n 129 disp(sqrt(n))
  • end
  • equivalent to
  • using implied loop
  • n 129
  • disp(sqrt(n))
  • Fill vector with values of cos(x)
  • explicit for loop
  • for k 1101
  • x (k-1)2pi/100
  • y(k) cos(x)
  • end
  • equivalent to
  • using implied loop
  • xlinspace(0,2pi,101)
  • y cos(x)

12
Examples
  • Display the log of a set of values read from a
    file.
  • load data.txt
  • for x data
  • logval log(x)
  • disp('Log of ', num2str(x), ' is ',
  • num2str(logval))
  • end

13
Examples
  • Now let's do our earlier iteration example
  • data 3,4,1,-3,8,6,-5,11
  • val 5
  • Loop through data
  • total 0
  • for n 1length(data)
  • if data(n)gtval
  • total total data(n)
  • end
  • end

Notice that in this case we can combine the
comparison and the summing in the same pass,
whereas the spreadsheet and implied loop
solutions first created a set of values bigger
than val, and then summed them up. A less
efficient for loop implementation could copy
that approach
14
Examples
  • First, create a vector of the big values
  • k 0 counter for large values
  • for n 1length(data)
  • if data(n)gtval
  • k k1
  • bigdata(k) data(n)
  • end
  • end
  • Now add up the big values
  • total 0
  • for n 1length(bigdata)
  • total total bigdata(n)
  • end

15
Standard Loop Structure
  • Programmed loop problems can be solved with the
    following general structure
  • pre-loop initialization
  • set up the problem, initialize variables,
    initialize counters, etc.
  • loop control initialize, increment/modify, test
  • usually a loop variable is specified, along with
    its initial value, increment value for each pass
    through the loop, and a test on the variable for
    when to exit the loop)
  • loop body
  • the instructions that are executed each pass
    through the loop
  • post-loop cleanup
  • stuff that needs to be done when the loop is
    exited

16
Standard Loop Structure Example
  • Example Disp. of neg. values in data array
  • data 3,4,1,-3,8,6,-5,11
  • pre-loop initialization
  • counter 0
  • loop control
  • for n 1length(data)
  • loop body
  • if data(n)lt 0
  • counter counter 1
  • end
  • end
  • post-loop cleanup
  • disp('Number of negative values is ')
  • disp(counter)
  • Programmed loop problems can be solved with the
    following general structure
  • pre-loop initialization
  • loop control initialize, increment/modify, test
  • loop body
  • post-loop cleanup

17
Well-known for Loop examples
  • Find maximum value in a vector
  • load data.txt
  • maximum data(1) maximum so far
  • for n 2length(data)
  • if data(n)gtmaximum
  • maximum data(n) replace with new
    maximum
  • end
  • end
  • Of course, there is also a quick function for
    that
  • maximum max(data)

18
Well-known for Loop examples
  • Search for a specific value in a vector
  • load data.txt
  • target input('Enter value to search for')
  • found 0 Initialize flag to false
  • for n 1length(data)
  • if data(n)target
  • found 1
  • break
  • end
  • end
  • Display result
  • if(found)
  • disp('Value was found.')
  • else
  • disp('Value was NOT found.')
  • end

A later slide in this file will formally
introduce this break command, which pops us out
of the for loop, and saves some time.
19
Well-known for Loop examples
  • Search for a specific value in a vector
  • Again, there is a faster way of doing this using
    find()
  • load data.txt
  • target input('Enter value to search for')
  • found length(find(datatarget))
  • Display result
  • if(found)
  • disp('Value was found.')
  • else
  • disp('Value was NOT found.')
  • end

20
for Loop to Vectorize a Function
  • Recall that we had a problem using an if
    statement with a vector in a function, so we
    learned how to insist on a scalar argument. The
    example performed an absolute value function.
  • function y myabs(x)
  • Test for scalar
  • if length(x)1
  • error('Input variable must be scalar.')
  • end
  • Input is scalar, proceed.
  • if xgt0
  • y x
  • else
  • y -x
  • end

21
for Loop to Vectorize a Function
  • Now we can use a for loop to provide the
    iteration needed with an if statement. The
    following is the same absolute value function,
    but now with the ability to handle vectors.
  • function y myabs(x)
  • Assume x, and thus y, are vectors
  • for n 1length(x)
  • if x(n)gt0
  • x(n) is a scalar, so there is no problem
  • y(n) x(n)
  • else
  • y(n) -x(n)
  • end
  • end

22
for Loop to Vectorize a Function
  • Another example Define this function as
    filteredpulse(t)
  • y 0 for tlt0
  • y 1 exp(-t) for 0 lt t lt a
  • y (1-exp(-a)) exp(a-t) for t gt a
  • function y filteredpulse(t,a)
  • for n 1length(t)
  • if t(n)lt0
  • y(n) 0
  • elseif t(n)gt 0 t(n) lt a
  • y(n) 1-exp(-t(n))
  • else
  • y(n) (1-exp(-a))exp(a-t(n))
  • end
  • end

23
Language Specific Questions for Explicit Loops
  • What is the value of the loop index when the loop
    is complete?
  • Is the loop ever skipped, or is it always
    executed at least once?
  • What happens when you modify the loop index in
    the body of the loop?
  • What if the loop control is a matrix instead of a
    vector?

The answers for these questions depend on what
language we are programming in. Lets answer
these questions for MATLAB.
24
Operational Issues with a for loop 1
  • What is value of loop index when loop is
    complete?
  • Next Value or Last Value?
  • for n15
  • disp(n)
  • end
  • disp(n)

Output will be 1 2 3 4
5 5
Upon leaving the loop, the loop index takes the
last value it had, during the last pass through
the loop.
25
Operational Issues with a for loop 2
  • What happens if control vector is "empty"?
  • Body skipped or execute once?
  • for n1-5
  • disp(n)
  • end
  • disp(n)

Output will be
The body is skipped, and the loop variable does
not even take on one value.
26
Operational Issues with a for loop 3
  • 1
  • 3
  • 2
  • 4
  • 3
  • 5
  • 4
  • 6
  • 5
  • 7
  • 7
  • What happens if loop index is changed inside
    body?
  • for n15
  • disp(n)
  • nn2
  • disp(n)
  • end
  • disp(n)

The loop index gets reset at the beginning of
each pass through the body of the loop.
27
Operational Issues with a for loop 4
  • Can loop control be a matrix rather than a vector?

ans 2 1 1 2 ans 2
1 3 4 ans 2 1 5
6
for nA size(n) disp(n) end
The loop index will take on values of a
succession of column vectors. In this case, with
three columns, there will be three passes through
the body of the loop.
28
General Rule for for loops
  • Do NOT explicitly change the control variable
    inside the loop!

29
How do we get out of a for loop?
  • break
  • Causes an immediate exit of a loop, from the loop
    it is currently executing.
  • Example
  • total0
  • for n11000
  • totaltotaln2
  • if(totalgt400)
  • break
  • end
  • end
  • disp('Smallest integer ',num2str(n))

Programming assignment Add the squares of the
integers until the accumulated sum is greater
than 400. Report the integer value where the sum
passes 400.
30
Skipping Part of a for loop
  • continue
  • This statement causes remaining statements in
    body of loop to be skipped.
  • Control passes to next execution of loop
  • total0
  • for n11000
  • if(mod(n,3)0)
  • continue
  • end
  • totaltotaln
  • end
  • disp(total)

Programming assignment Calculate the sum of all
integers from 1 to 1000 that are evenly divisible
by 3.
mod(x,y) is an integer operator that gives the
remainder when x is divided by y.
31
Standard Loop Problems
  • Counting the number of occurrences
  • Summing expressions
  • Multiplying expressions
  • Finding extreme values
  • "Vectorizing" a function
  • Finding a target
  • Early exit/use of a flag
  • Creating a new array of the same size
  • Creating a new array of a different size
  • Interchanging values in an array

32
Nested Loops
  • When a loop is contained in the body of another
    loop, we refer to them as nested loops.
  • All parts of the basic structure of a loop are
    still seen in each loop

33
Nested Loops
  • pre-outer loop initialization
  • outer loop control
  • outer loop body
  • pre-inner loop initialization
  •   inner loop control
  •   inner loop body
  •   inner loop cleanup
  • outer loop body resumes
  •  outer loop cleanup

This is the inner loop.
34
Nested Loops Matrices
  • Whereas single loop problems frequently involve
    vectors, nested loops are usually required when
    processing matrices.
  • The outer loop iterates over the rows, while the
    inner loop iterates over the elements in each
    row, that is, the elements in each column of that
    row.
  • Or the outer loop iterates over the columns while
    the inner loop iterates over the elements in each
    column , that is, the elements in each row of
    that column.

35
Nested Loops Matrices
  • It is recommended that we solve from the "inside
    out"figure out what the innermost loop must do
    with each row or column, and then enclose it in a
    loop over all the rows or columns.

36
Example Given array A, how many rows sum to more
than 100?
  • Solution inner loop sum the values in a row
  • Outer loop count the number of times the sum
    exceeds 100.

37
Example of manipulation of an array
  • nrows ncols size(A)
  • count 0
  • for m1nrows for each row
  • total 0
  • for n1ncols each column in the row
  • total total A(m,n)
  • end
  • if total gt100
  • count count 1
  • end
  • end
  • disp('Number of times')
  • disp(count)

38
Example Given an array data, append to each
column the average of the values in that column
  • Solution
  • Inner loop compute average value of the column
  • Outer loop do so for each column append

39

Example of manipulation of an array
  • nrows ncols size(data)
  • for n1ncols for each column
  • total 0
  • for m1nrows go down the column
  • total total data(m,n)
  • end
  • average total /nrows average of that column
  • data(nrows1,n) average
  • end

40

Example of manipulation of an array
  • nrows ncols size(data)
  • for n1ncols for each column
  • total 0
  • for m1nrows go down the column
  • total total data(m,n)
  • end
  • average total /nrows average of that column
  • data(nrows1,n) average
  • end

For this course, when you are told not to use
implicit looping, an automatic exception to this
instruction is the use of the size and length
commands to get information about vectors and
arrays.
41

Example using Nested Loops, with no Implicit Loops
  • You have a table of temperature data for a year,
    in degrees. Each row represents one week of noon
    temperatures in Houston, one per day. How many
    weeks had a maximum temperature that was at least
    5 degrees higher than the average temperature for
    that week?

Approach Inner loop Compute average and
maximum for that row (week). (extreme value,
extreme initial value) Outer loop Do so for each
row, counting the times when the row maximum is 5
degrees more than the row average. (counter)
42

while Loops
  • while loops are a different way of looping
  • for loop
  • number of passes through the loop is known in
    advance
  • controlled by the loop index variable
  • while loop
  • number of passes through the loop is not known
    in advance
  • depends on a special condition that is
    re-evaluated after each pass through the loop

43

while Loops
  • while loop
  • number of passes through the loop is not known
    in advance
  • depends on a special condition that is
    re-evaluated after each pass through the loop

44

while Loops
  • The MATLAB while statement is
  • while logical-expression
  • statements
  • end

45

while Loops
  • Compared to the standard loop structure described
    earlier, elements of loop control section
    (initialize, increment/modify, test) are now
    distributed.
  • The "initialize operation must be part of the
    loop initialization section
  • The "increment/test operation is done in the
    loop body
  • The while instruction itself contains the "test
    operation

46

while Loops
  • Example A for loop implemented with a while
    loop might look like this
  • for x 18
  • y(x) 2 x
  • end
  • disp(y)
  • x 1
  • while x lt 8
  • y(x) 2 x
  • x x 1
  • end
  • disp(y)

47

Multilevel Branching Switch
  • The switch command is an alternative to an
    if-elseif-elseif-else sequence.
  • The format is
  • switch input-expression
  • case value1
  • statement group 1
  • case value2
  • statement group 2
  • .
  • .
  • .
  • otherwise
  • statement group n
  • end

This input-expression must be a scalar or string.
48

Multilevel Branching Switch
  • The switch command is an alternative to an
    if-elseif-elseif-else sequence.
  • The format is
  • switch input-expression
  • case value1
  • statement group 1
  • case value2
  • statement group 2
  • .
  • .
  • .
  • otherwise
  • statement group n
  • end

When value1 is equal to input-expression, this
statement group is executed.
49

Multilevel Branching Switch
  • The switch command is an alternative to an
    if-elseif-elseif-else sequence.
  • The format is
  • switch input-expression
  • case value1
  • statement group 1
  • case value2
  • statement group 2
  • .
  • .
  • .
  • otherwise
  • statement group n
  • end

When value2 is equal to input-expression, this
statement group is executed.
50

Multilevel Branching Switch
  • The switch command is an alternative to an
    if-elseif-elseif-else sequence.
  • The format is
  • switch input-expression
  • case value1
  • statement group 1
  • case value2
  • statement group 2
  • .
  • .
  • .
  • otherwise
  • statement group n
  • end

When none of the cases is equal to
input-expression, this statement group is
executed.
51

Multilevel Branching Switch
  • The switch command is an alternative to an
    if-elseif-elseif-else sequence.
  • The format is
  • switch input-expression
  • case value1
  • statement group 1
  • case value2
  • statement group 2
  • .
  • .
  • .
  • otherwise
  • statement group n
  • end

The otherwise statement is optional.
52

switch and while?
  • If you are thinking that we can do all of the
    while loop stuff with for loops, you are
    correct.
  • If you are thinking that we can do all of the
    switch branching stuff with if statements,
    you are correct.

We dont need these. We can use these to improve
readability of the code. It is about clarity,
not logic.
Write a Comment
User Comments (0)
About PowerShow.com