0% found this document useful (0 votes)
6 views20 pages

Chapter 9

This document covers repetition structures in MATLAB, specifically focusing on for loops and while loops. It explains the components of loops, provides examples of their usage, and discusses the differences between for and while loops. Additionally, it includes information on early termination of loops using break and continue statements, as well as nested loops.

Uploaded by

7n5m0ud08
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views20 pages

Chapter 9

This document covers repetition structures in MATLAB, specifically focusing on for loops and while loops. It explains the components of loops, provides examples of their usage, and discusses the differences between for and while loops. Additionally, it includes information on early termination of loops using break and continue statements, as well as nested loops.

Uploaded by

7n5m0ud08
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

GE 209 - COMPUTER PROGRAMING USING

MATLAB
Lectures
Chapter 9
Repetition Structures
Introduction
 The previous chapter described selection structures; in this chapter we will focus on repetition
structures (Loops).
 MATLAB supports two different types of loops: the for loop (for-end loop ) and the while loop
(while-end loop).

Repetition structures are often called loops. All loops consist of five basic parts.

• A parameter to be used in determining whether or not to end the loop.

• Initialization of this parameter.

• A way to change the parameter each time through the loop. (If you don’t change it, the loop will never

stop executing.)

• A comparison, using the parameter, to a criterion used to decide when to end the loop.

• Calculations to do inside the loop.


9.1 For Loops

 The for loop is used to repeat a set of commands for a specified number of times. It starts with for
and end with the word end
 In a loop, the execution of a command, or a group of commands, is repeated several times
consecutively. Each round of execution is called a pass.
 In for-end loops: The number of passes is specified when the loop starts.
 The general form of a for loop is:

For example, if k = 1:2:9, there are five loops, and the corresponding values of k are 1, 3, 5, 7, and 9.
Notes about for Loops
 The increment s can be negative (i.e.; k = 25:–5:10 produces four passes with k = 25, 20, 15, 10).
 If the increment value s is omitted, the value is 1 (default) (i.e.; k = 3:7 produces five passes with k = 3, 4, 5, 6, 7).
 If f = t, the loop is executed once.
 If f > t and s > 0, (5:1:2) or if f < t and s < 0, (2:-1:5) the loop is not executed.
 If the values of f, s, and t are such that k cannot be equal to t, then:
• if s is positive, the last pass is the one where k has the largest value that is smaller than t (i.e., k = 8:10:50 produces
five passes with k = 8, 18, 28, 38, 48).
• if s is negative, the last pass is the one where k has the smallest value that is larger than t.
 Each for command in a program must have an end command.
 When the loop ends, the loop index variable (k) has the value that was last assigned to it.

Simple Examples: V=
a=
1 1
5
for k=1:3:10 V= for k = [1,3,7]
a=
x = k^2; 4 16 a=5^k
125
V=[k,x] V= end
a=
end 7 49
78125
V=
10 100
for index = [array]
A common way to use a loop is in defining a new matrix
commands to be executed
end

Example 1 Example 2
1 2 3
Alternatively: k= 1 4 9
for k = 1:5 k = 1:5 1 8 27
a(k) = k^2 a = k.^2 for k = [1,2,3; 1,4,9; 1,8,27]
end a = k’
a=
end
a= 1 4 9 16 25
1 a=
a= 1 1 1
1 4 a=
a= 2 4 8
If the index k is a matrix, MATLAB
1 4 9 a=
a= uses an entire column as the index 3 9 27
1 4 9 16
of each pass
a= 1 1 1
1 4 9 16 25 2 4 8
3 9 27
Example 3 Create a table that converts angle values from degrees to
radians, from 0 to 360 degrees, in increments of 10 degrees.
% Create a table of degrees to radians
clear
%Use a for loop for calculations
for k=1:36
deg(k) =k*10;
rad(k) = deg(k)*pi/180;
end
% Create a table
t = [deg;rad]
disp('Degree to Radians')
fprintf('%8.0f %8.2f \n',t)

How many students have


Example 4 scores more than 90
scores = [76,45,98,97];
count = 0;
for k=1:length(scores)
if scores(k)>90
count = count + 1;
end
end
disp(count)
Array pre-allocation A = zeros(Nrow, 1); % Array pre-allocation
– Consider a single for loop of the form: for r = 1:Nrow
Statements
A(r) = ...
end

– where Nrow is a positive integer that previously has been assigned a numerical value.
– The addition of the array assignment statement, A = zeros(Nrow, 1), ensures that the loop executes at
maximum speed.
Enter a positive integer < 15: 9
Example 1 2 3 4 5 6 7 8 9

N = input('Enter a positive integer < 15: '); 10 11 12 13 14 15 16 17 18


Matr = zeros(N, N); 19 20 21 22 23 24 25 26 27
for r = 1:N
28 29 30 31 32 33 34 35 36
Matr(r,1:N) = ((r-1)*N+1):r*N;
end 37 38 39 40 41 42 43 44 45
disp(Matr) 46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63
64 65 66 67 68 69 70 71 72
73 74 75 76 77 78 79 80 81
Other examples: (nested loops)
Examples 2
Examples 1
Determine the maximum (each column) of the
following matrix:
Create the following vector Y of 50 elements:
1 2 6 3
𝑘 2 + 5𝑘 − 10 𝑓𝑜𝑟 𝑘≤9
4 8 2 1
𝑌(𝑘) = ൞ 10𝑘 + 5 𝑓𝑜𝑟 9 < 𝑘 ≤ 20 12 18 3 5
1 𝑓𝑜𝑟 𝑘 > 20 6 4 2 13

n= 50; x=[1 2 6 3;4 8 2 1;12 18 3 5;6 4 2 13];


Y = zeros(n,1); % Pre-allocation [rows,cols]=size(x);
for k=1:n maximum=zeros(1,cols); % Pre-allocation
if k<=9 for k=1:cols
Y(k)=k^2+5*k-10; maximum(k)=x(1,k);
elseif k<=20 for j=1:rows
Y(k)=10*k+5; if x(j,k)>maximum(k)
else maximum(k)=x(j,k);
Y(k)=1; end
end end
end end
disp(Y) maximum % Screen display
9.2 WHILE LOOPS
 The while loops are used when looping is needed but the number of passes is not known in advance.
 In while-end loops the number of passes is not specified when the looping process starts.
 The while loop repeats one or more statements an indefinite number of times, leaving the loop only when a
specified condition (criterion) has been satisfied.

 The first line is a while statement that includes a conditional expression.


 When the program reaches this line, if the condition is false (0), MATLAB skips to the end statement.
 If the condition is true (1), MATLAB executes the group of commands that follow between the while and end
Then MATLAB jumps back to the while command and checks the conditional expression again.
Notes about while Loops
 While loops are similar to for loops.
 The big difference is the way MATLAB decides how many times to repeat the loop:
• While loops continue until some criterion is met.
• In while loop, you must change or update the criterion each time through the loop (otherwise the loop will
not stop)
• Whereas, in for loop, the variable index change, each pass, automatically, according to its definition (k=f:s:t)
 In general, when using the while loop, a counter k, may be initialized before starting the loop and then
incremented by 1 every pass. This will provide the number of passes executed

Example k = 0;
for k = 1:3 while k<3
a = 5^k k = k+1;
end a = 5^k
end
a= 5
a= 25 a= 5
a= 125 a= 25
a= 125
Examples using while Loop

Example 1: for loop approach while loop approach

How many students have scores scores = [76,45,98,97]; scores = [76,45,98,97];


more than 90 count = 0; count = 0;
for k=1:length(scores) k = 0;
if scores(k)>90 while k< length(scores)
count = count + 1; k = k+1;
end if scores(k)>90
end count = count + 1;
disp(count) end
end
disp(count)

Example 2: x = input('Enter a positive value of x')


while (x<=0)
Calculate the log base 10 of a disp('log(x) is not defined for negative numbers')
number x = input('Enter a positive value of x')
end
y = log10(x);
fprintf('The log base 10 of %4.2f is %5.2f \n',x,y)
Examples using while Loop (cont.)
Example 3:
MATLAB script
Approximation to 
xo = 1/sqrt(2); yo = 1/2; n = 0;
The following expression converges to while abs(1/pi - yo) > 1e-15
1/ when starting from: xo = (1-sqrt(1-xo^2))/(1+sqrt(1-xo^2));
yo = yo*(1+xo)^2-2^(n+1)*xo;
𝑥0 = 1Τ 2 𝑎𝑛𝑑 𝑦0 = 1/2 n = n+1;
end
yn 1  yn 1  xn 1   2n 1 xn 1 n  0,1,2,...
2 fprintf(1, 'For n = %2.f, |1/pi-y_(n+1)| =
%5.4e\n', n-1, abs(1/pi - yo))

where
1  1  xn2 Execution of this script results in:
xn 1 
1  1  xn2 For n = 3,
|1/pi-y_(n+1)| = 4.9960e-016
We shall show that the difference |1/  y4| is
less than 1015.
Example 4: The alternating harmonic series

−1 𝑘+1 1 1 1 1
෍ = 1 − + − + − ⋯ ⋯ = ln(2)
𝑘 2 3 4 5
𝑘=1

%% Calculating the Alternating Harmonic Series


clear,clc
% Define the first two elements in series
y(1)=1; y(2)=-1/2;
%Calculate the first two cumulative sums
total(1)=y(1); total(2)=total(1) + y(2);
k=3;
while (abs(total(k-1)-total(k-2))>.001)
y(k)=(-1)^(k+1)/k;
total(k) = total(k-1) + y(k);
k = k+1;
end
fprintf('Sequence converges when final element is equal to
%8.3f\n',y(k-1))
fprintf('At which point value of the series is %5.4f
\n',total(k-1))
fprintf('This compares to value of the ln(2), %5.4f \n',log(2))
fprintf('The sequence took %3.0f terms to converge \n',k)
%% Plot the results
semilogx(total)
title('Value of the Alternating Harmonic Series')
xlabel('Number of terms'); ylabel('Sum of the terms')

Example 4 (cont.): The alternating harmonic series −1 𝑘+1 1 1 1 1
෍ = 1 − + − + − ⋯ ⋯ = ln(2)
𝑘 2 3 4 5
𝑘=1
9.3 BREAK and CONTINUE
• Early Termination of Either a for or while Loop:
– The break function is used to terminate either a for or while loop prematurely (while the
comparison in the first line is still true).
– A break statement will cause termination of the smallest enclosing while or for loop.
– The continue function is similar to break; however, instead of terminating the loop, the
program just skips to the next pass.
n = 0; n = 0;
While (n<10) while(n<10)
n = n+1; n = n+1;
a = input('Enter a value greater than 0:'); a = input('Enter a value greater than 0:');
if(a<=0) if(a<=0)
disp(‘Enter a positive number only') disp('You must enter a positive number')
disp('This program will terminate') disp('Try again')
break continue
end end
disp('The natural log of that number is') disp('The natural log of that number is')
disp(log(a)) disp(log(a))
end end

If the value of a is positive, the program continues if you enter a negative number, the program lets you
and another pass through the loop occurs, until n is try again—until the value of n is finally greater than
finally greater than 10. 10.
9.5 NESTED LOOPS
 It is often useful to nest loops inside other loops. This is actually how many of the MATLAB built-in
functions operate.
 Loops and conditional statements can be nested within other loops or conditional statements. This
means that a loop and/or a conditional statement can start (and end) within another loop or conditional
statement.
 There is no limit to the number of loops and conditional statements that can be nested. It must be
remembered, however, that each if, case, for, and while statement must have a corresponding end
statement.
Example 1:
• Consider the following matrix: x = [1 2 6 3;4 8 2 1;12 18 3 5;6 4 2 13]
• If we use the max function:
max(x)
ans =
12 18 6 13

• Now, we can use that information to create the external for loop, which we program to execute once for each
column in the array. Then, we define a provisional value for the maximum, based on the first value in each
column. Finally, we can use an internal for loop, which will execute once for each row in the array.

for k=1:cols
maximum(k)=x(1,k)
for j=1:rows
if x(j,k)>maximum(k)
maximum(k)=x(j,k);
end
end
end
• Example 2: Dot Multiplication of Matrices
– We shall perform the dot multiplication of two matrices A and B of the same order.

– The script is equivalent to A.*B

– We will illustrate the procedure using the magic matrices: A = magic(3) and B = A'.

– However, in general, before the multiplication can be performed, one must ensure that the order of the
matrices is equal. A = magic(3); B = A';
[rA, cA] = size(A);
[rB, cB] = size(B);
M = zeros(rA, cA);
for c = 1:cA
if (rA~=rB)||(cA~=cB)
error('Matrices must be the same size')
break
end
for r = 1:rA
M(r, c) = A(r, c)*B(r, c);
end
end
disp(M)
Example 3: Tracing the execution of a program
Follow the execution of this program by filling the table and giving the final output for n=4

clear; clc i j A(i,j)


n=4 1 1 1
for i = 1:n
for j = 1:n
if i == 1
A(i,j) = 1;
elseif j == 1
A(i,j) = 1;
else
A(i,j) = A(i,j-1) + A(i-1,j);
end
end
end
A

A=
1 1 1 1
1 2 3 4
1 3 6 10
1 4 10 20

You might also like