
Lecture 8
Lecture 8
Loops for repetitive
Loops for repetitive
computations
computations
The
The for
for loop construct
loop construct
© 2007 Daniel Valentine. All rights reserved. Published by
Elsevier.
1
1

Concept of the
Concept of the for
for loop
loop
The
The
for l
for loop
oop is a MATLAB construct that
is a MATLAB construct that
allows a sequence of MATLAB statements to be
allows a sequence of MATLAB statements to be
executed more than once
executed more than once.
.
The
The
for l
for loop
oop
repeats a block of commands
repeats a block of commands
for a specified number of times; the specified
for a specified number of times; the specified
number is
number is established before
established before the loop is
the loop is
executed.
executed.
2
2

Construction of
Construction of for
for loops
loops
The
The for
for loop construct:
loop construct:
for index = [
for index = [range of values in array format]
range of values in array format]
command #1
command #1
command #2
command #2
command #3
command #3
...
...
end
end
3
3

for n = 1:5
for n = 1:5
fprintf('The
fprintf('The value of n is now %
value of n is now %d
d\
\n',n
n',n);
);
end
end
A simple example
A simple example
__________________________________
Note: After executing this script, change the steps n = 1:5 to n
= 1:.5:5 and execute the script to show that n does not have
to be an integer.
The output should look like:
The output should look like:
The value of n is now 1
The value of n is now 1
The value of n is now 2
The value of n is now 2
The value of n is now 3
The value of n is now 3
The value of n is now 4
The value of n is now 4
The value of n is now 5
The value of n is now 5
4
4

Hands on
Hands on
vector_1 contains the values of n, i.e.:
vector_1 contains the values of n, i.e.:
vector_1 = [1 2 3 4 5]
vector_1 = [1 2 3 4 5]
vector_2 contains the squares of n, i.e.:
vector_2 contains the squares of n, i.e.:
vector_2 = [1 4 9 16 25]
vector_2 = [1 4 9 16 25]
You can use a loop to define, element by element,
You can use a loop to define, element by element,
a vector; this illustrates how a for loop works. Try
a vector; this illustrates how a for loop works. Try
the following exercise:
the following exercise:
5
5
for n=1:5
for n=1:5
fprintf('The
fprintf('The value of n is now %
value of n is now %d
d\
\n',n
n',n);
);
vector_1(n)=n;
vector_1(n)=n;
vector_2(n)=n^2;
vector_2(n)=n^2;
end
end

