Vous êtes sur la page 1sur 19

# Loops

## Loops are MATLAB constructs that permit us to

execute a sequence of statements more than
once. There are two basic forms of loop
constructs:

## The major difference between these two types of

loop 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 starts.
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

while expression
...
... Code block
...
end
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

## for index = expr

...
... Body
...
end
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 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.
for ii = 1:10 for ii = 1:2:10
Statement 1 Statement 1
... ...
Statement n Statement n
end end

## for ii = [5 9 7] for ii = [1 2 3;4 5 6]

Statement 1 Statement 1
... ...
Statement n Statement n
end end

## Number of repetitions=3 Number of repetitions=3

One for each column vector.
Now that we have seen examples of a for loop in
operation, we must examine some important
details required to use for loops properly.

## 1) Indent the bodies of loops.

It is not necessary to indent the body of a for loop
as we have shown above. MATLAB will
recognize the loop even if every statement in it
starts in column 1. However, the code is much
more readable if the body of the for loop is
indented, so you should always indent the
bodies of loops.
2) Don’t modify the loop index within the body of a loop.

## The loop index of a for loop should not be modified

anywhere within the body of the loop. The index variable
is often used as a counter within the loop, and modifying
its value can cause strange and hard-to-find errors.

## The example shown below is intended to initialize the

elements of an array, but the statement “ii = 5” has been
accidentally inserted into the body of the loop. As a
result, only a(5) is initialized, and it gets the values that
should have gone into a(1), a(2), etc.
for ii = 1:10
...
ii = 5; % Error!
...
a(ii) = <calculation>
end
3. Preallocating Arrays.

## We learned in Chapter 2 that it is possible to extend an existing array

simply by assigning a value to a higher array element.
For example, the statement

arr = 1:4;

statement
arr(8) = 6;

## is executed, the array will be automatically extended to eight elements

and will contain the values [1 2 3 4 0 0 0 6].

## Unfortunately, each time that an array is extended, MATLAB has to

(1) create a new array,
(2) copy the contents of the old array to the new longer array,
(3) Add the new value to the array, and then
(4) delete the old array.
This process is very time consuming for long arrays.
On the other hand, if the array is preallocated to its maximum
size before the loop starts executing, no copying is required,
and the code executes much faster. The code fragment
shown below shows how to preallocate an array before the
starting the loop.

square = zeros(1,100);
for ii = 1:100
square(ii) = ii^2;
end

4) Vectorizing Arrays

## It is often possible to perform calculations with either for

loops or vectors. For example, the following code fragment
calculates the squares, square roots, and cube roots of all
integers between 1 and 100 using a for loop.
for ii = 1:100
square(ii) = ii^2;
square_root(ii) = ii^(1/2);
cube_root(ii) = ii^(1/3);
end
The following code fragment performs the same calculation with
vectors.

ii = 1:100;
square = ii.^2;
square_root = ii.^(1/2);
cube_root(ii) = ii.^(1/3);

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! In MATLAB, the process of
replacing loops by vectorized statements is known as vectorization.
Vectorization can yield dramatic improvements in performance for
many MATLAB programs.
Break statement terminates the execution of a
loop and passes the control to the next
statement after the end of the loop

## Continue statement terminates the current

pass through the loop and returns control to
the top of the loop
Example: Example:

## for ii = 1:5 for ii = 1:5

if ii == 3; if ii == 3;
break; continue;
end end
fprintf('ii = %d\n',ii); fprintf('ii = %d\n',ii);
end end
disp(['End of loop!']); disp(['End of loop!']);

## When this program is executed, When this program is executed,

the output is the output is
» test_break » test_continue
ii = 1 ii = 1
ii = 2 ii = 2
End of loop! ii = 4
ii = 5
End of loop!
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.
Output:
for ii = 1:3 1*1=1
for jj = 1:3 1*2=2
product = ii * jj; 1*3=3
fprintf('%d * %d = %d\n',ii,jj,product); 2*1=2
end 2*2=4
end 2*3=6
3*1=3
3*2=6
3*3=9
If for loops are nested, they should have independent loop index
variables. If they have the same index variable, then the inner loop
will change the value of the loop index that the outer loop just set.
If a break or continue statement appears inside a set of nested
loops, then that statement refers to the innermost of the loops
containing it. For example, consider the following program:

## for ii = 1:3 Output:

for jj = 1:3 1*1=1
if jj == 3; 1*2=2
break; End of inner loop
end 2*1=2
product = ii * jj; 2*2=4
fprintf('%d * %d = %d\n',ii,jj,product); End of inner loop
end 3*1=3
fprintf('End of inner loop\n'); 3*2=6
end End of inner loop
fprintf('End of outer loop\n'); End of outer loop
For example, consider the following
statements:
a = [1 2 3; 4 5 6; 7 8 9];
b = a > 5;
These statements produce
1 2 3 0 0 0
a   4 5 6 b  0 0 1
   
7 8 9 1 1 1
   

## a is a double array, b is a logical array

Logical arrays have a very important special property—they can
serve as a mask for arithmetic operations. A mask is an array that
selects the elements of another array for use in an operation. The
specified operation will be applied to the selected elements and
not to the remaining elements.
For example, suppose that arrays a and b are as defined
previously. Then the statement

a(b) = sqrt(a(b))

will take the square root of all elements for which the logical array
b is true and leave all the other elements in the array unchanged.

a=
1.0000 2.0000 3.0000
4.0000 5.0000 2.4495
2.6458 2.8284 3.0000

## This is a very fast and very clever way of performing an operation

on a subset of an array without needing loops and branches.
The following two code fragments both take the square root of all
elements in array a whose value is greater than 5, but the
vectorized approach is more compact and elegant than the loop
approach.

## for ii = 1:size(a,1) b = a > 5;

for jj = 1:size(a,2) a(b) = sqrt(a(b));
if a(ii,jj) > 5
a(ii,jj) = sqrt(a(ii,jj));
end
end
end
for ii = 1:size(a,1) The vectorized code for this
for jj = 1:size(a,2) operation is
if a(ii,jj) > 5
a(ii,jj) = sqrt(a(ii,jj)); b = a > 5;
else a(b) = sqrt(a(b));
a(ii,jj) = a(ii,jj)^2; a(~b) = a(~b).^2;
end
end
end