Intro To MATLAB - Week 8 - Loops

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 25

Intro to MATLAB

WEEK 8
Loops

 Loops are MATLAB constructs that permit us to execute a sequence of statements


more than once.

 MATLAB programs that use loops often process very large amounts of data, and
the programs need an efficient way to read that data for processing.
Types of Loops

 There are two basic forms of loop constructs: while loops and for loops.

 The major difference between these two types of loops is in how the repetition is
controlled. The code in a while loop is repeated an indefinite number of times
until some user-specified condition is satisfied.
 By contrast, the code in a for loop is repeated a specified number of times, and the
number of repetitions is known before the loops start.
Vectorization

 Alternate and faster way to perform the same function as many MATLAB for
loops. Will show an example later on in the slides.
The while Loop

 A while loop is a block of statements that are repeated indefinitely as long as


some condition is satisfied. The general form of a while loop is:
The while Loop

 The controlling expression produces a logic al value. If the expression is true, the
code block will be executed, and then control will return to the while statement. If
the expression is still true, the statements will be executed again. This process will
be repeated until the expression becomes false. When control returns to the while
statement and the expression is false, the program will execute the first statement
after the end.
Example
The for Loop

 The for loop is a loop that executes a block of statements a specified number of
times. The for loop has the form:
The for Loop

 The index is the loop variable (also known as the loop index) and expr is the loop
control expression, whose result is an array. The columns in the array produced by
expr are stored one at a time in the variable index and then the loop body is
executed, so that the loop is executed once for each column in the array produced
by expr. The expression usually takes the form of a vector in shortcut notation:
first : incr : last.
The for Loop

 The statements between the for statement and the end statement are known as the
body of the loop. They are executed repeatedly during each pass of the for loop.
The for Loop

 The for loop construct functions as follows:

 1. At the beginning of the loop, MATLAB generates an array by evaluating the


control expression.
 2. The first time through the loop, the program assigns the first column of the array
to the loop variable index, and the program executes the statements within the body of
the loop.
 3. After the statements in the body of the loop have been executed, the program
assigns the next column of the array to the loop variable index, and the program
executes the statements within the body of the loop again.
 4. Step 3 is repeated over and over as long as there are additional columns in the
array.
Examples to make it clearer

 Consider:
 for ii = 1 : 10
 Statement 1
 …
 Statement n
 end
 In this loop, the control index is the variable ii. In this case, the control expression
generates a 1 X 10 array, so statements 1 through n will be executed 10 times. The loop
index ii will be 1 the first time, 2 the second time, and so on. The loop index will be 10 on
the last pass through the statements. When control is returned to the for statement after the
tenth pass, there are no more columns in the control expression, so execution transfers to
the first statement after the end statement. Note that the loop index ii is still set to 10 after
the loop finishes executing.
Second Clarification

 for ii = 1 : 2 : 10
 Statement 1
 …
 Statement n
 end
 In this case, the control expression generates a 1 X 5 array, so statements 1
through n will be executed 5 times. The loop index ii will be 1 the first time, 3 the
second time, and so on. The loop index will be 9 on the fifth and last pass through
the statements. When control is returned to the for statement after the fifth pass,
there are no more columns in the control expression, so execution transfers to the
first statement after the end statement. Note that the loop index ii is still set to 9
after the loop finishes executing.
Third Clarification

 for ii = [5 9 7]
 Statement 1
 …
 Statement n
 end
 Here, the control expression is an explicitly written 1 3 3 array, so statements 1
through n will be executed 3 times with the loop index set to 5 the first time, 9 the
second time, and 7 the final time. The loop index ii is still set to 7 after the loop
finishes executing.
Final Consideration

 For ii = [1 2 3; 4 5 6]
 Statement 1
 …
 Statement n
 end
 In this case, the control expression is a 2 X 3 array, so statements 1 through n will
be executed 3 times. The loop index ii will be the column vector [1 ; 4] the first
time, [2 ; 5] the second time, and [3 ; 6] the third time. The loop index ii is still set
to [3 ; 6] after the loop finishes executing. This example illustrates that a loop
index can be a vector.
Factorial Function Example
Example
Vectorization: A Faster Alternative to
Loops

 Here, the loop is executed 100 times, and one value of each output array is
calculated during each cycle of the loop.
 MATLAB offers a faster alternative for calculations of this sort: vectorization.
Instead of executing each statement 100 times, MATLAB can do the calculation
for all the elements in an array in a single statement. Because of the way
MATLAB is designed, this single statement can be much faster than the loop and
perform exactly the same calculation.
Vectorization: A Faster Alternative to
Loops
 For example, the following code fragment uses vectors to perform the same
calculation as the loop shown previously. We first calculate a vector of the indices
into the arrays and then perform each calculation only once, doing all 100
elements in the single statement.
 Even though these two calculations produce the same answers, they are not
equivalent. The version with the for loop can be more than 15 times slower than
the vectorized version! This happens because the statements in the for loop must
be interpreted and executed a line at a time by MATLAB during each pass of the
loop. In effect, MATLAB must interpret and execute 300 separate lines of code.
In contrast, MATLAB only has to interpret and execute 4 lines in the vectorized
case. Since MATLAB is designed to implement vectorized statements in a very
efficient fashion, it is much faster in that mode.
Example
The break and continue Statements

 There are two additional statements that can be used to control the operation of
while loops and for loops: the break and continue statements. The break
statement terminates the execution of a loop and passes control to the next
statement after the end of the loop, and the continue statement terminates the
current pass through the loop and returns control to the top of the loop.
The break Statement

 If a break statement is executed in the body of a loop, the execution of the body
will stop and control will be transferred to the first executable statement after the
loop. An example of the break statement in a for loop is as follows:

 Execute!
The continue Statement

 If a continue statement is executed in the body of a loop, the execution of the


current pass through the loop will stop and control will return to the top of the
loop. The controlling variable in the for loop will take on its next value, and the
loop will be executed again. An example of the continue statement in a for loop is
as follows:

 Execute!
Nested Loops

 It is possible for one loop to be completely inside another loop. If one loop is
completely inside another one, the two loops are called nested loops. The
following example shows two nested for loops used to calculate and write out the
product of two integers.
Activity 6


 If we assume negligible air friction and ignore the curvature of the Earth, a ball that is thrown into the air from any point on
the Earth’s surface will follow a parabolic flight path. The height of the ball at any time t after it is thrown is given by given
equation:

 where yo is the initial height of the object above the ground, vy0 is the initial vertical velocity of the object, and g is the
acceleration due to the Earth’s gravity. The horizontal distance (range) traveled by the ball as a function of time after it is
thrown is given by equation:

 where x0 is the initial horizontal position of the ball on the ground and vx0 is the initial horizontal velocity of the ball. If the
ball is thrown with some initial velocity v0 at an angle of u degrees with respect to the Earth’s surface, then the initial
horizontal and vertical components of velocity will be:

 Assume that the ball is initially thrown from position sx0, y0 d 5 (0, 0) with an initial velocity v0 of 20 meters per second at
an initial angle of u degrees. Write a program that determines the horizontal distance traveled before it touches the ground
again. determine the horizontal distance traveled for all angles u from 0 to 90° in 1° steps. Finally, it should determine the
angle u that maximizes the range of the ball.

You might also like