Docsity

MATLAB Control Flow: For Loops and While Loops, Study notes of Engineering

Toggle sidebar
bg1
1
Chapter 13 Control Flow
13.1 For Loops
'For' Loops are one of several ways to control the order of execution of
MATLAB commands in an M-file. It (or something equivalent ) is a basic construct of
all high level programming languages. The 'For' Loop is used when a group of
MATLAB commands are to be executed a predetermined number of times. The 'For'
Loop commands are enclosed between the initial line which defines the loop variable and
an array of values for it to assume and the 'end' statement which signals the end of the
loop. The general form is
for x = array
(commands)
end
Example 13.1.1
A=[1 2; 3 4] % Create square matrix A
for i=1:5 % Set array values for loop variable i as 1,2,...,5
B=A^i % Compute matrix B from constant matrix A and loop variable i
end % for i
C=diag(diag(B)) % Create diagonal matrix C using diagonal from matrix B
A = 1 2
3 4
B = 1 2
3 4
B = 7 10
15 22
B = 37 54
81 118
B = 199 290
435 634
B = 1069 1558
2337 3406
C = 1069 0
0 3406
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download MATLAB Control Flow: For Loops and While Loops and more Study notes Engineering in PDF only on Docsity!

Chapter 13 Control Flow

13.1 For Loops

'For' Loops are one of several ways to control the order of execution of

MATLAB commands in an M- file. It (or something equivalent ) is a basic construct of

all high level programming languages. The 'For' Loop is used when a group of

MATLAB commands are to be executed a predetermined number of times. The 'For'

Loop commands are enclosed between the initial line which defines the loop variable and

an array of values for it to assume and the 'end' statement which signals the end of the

loop. The general form is

for x = array

(commands)

end

Example 13.1.

A=[1 2; 3 4] % Create square matrix A for i=1:5 % Set array values for loop variable i as 1,2,..., B=A^i % Compute matrix B from constant matrix A and loop variable i end % for i C=diag(diag(B)) % Create diagonal matrix C using diagonal from matrix B

A = 1 2

B = 1 2

B = 7 10

B = 37 54

B = 199 290

B = 1069 1558

C = 1069 0

Example 13.1.

for x=linspace(0,pi/2,4) % Set array values for loop variable x x y=sin(x) z=cos(x) end % for x

x = 0 y = 0 z = 1

x = 0. y = 0. z = 0.

x = 1. y = 0. z = 0.

x = 1. y = 1 z = 6.1232e-

The loop variable in a 'For' Loop is not required to be present in any of the loop

commands. If its not, all the loop commands are simply executed for each iteration of the

loop.

Example 13.1.

x=0; % Initialize x for k = 1: x=x+rand % Accumulate sum end % for k

x = 0. x = 1. x = 2. x = 2. x = 3.

The loop variable in a 'For' Loop should not appear by itself on the left side of an

assignment statement, i.e. it should not be reassigned because the loop will execute a

fixed number of times according to the array of values specified in the first line.

Example 13.1.

y(4)=0 % Preallocate memory for array y for n=1: n % Display value of loop variable y(n)=n*rand n=4 % This will not terminate the loop end

X =

indices = 2 5 10 11

i = 2 y = 8.

i = 5 y = 8.5293 7.

i = 10 y = 8.5293 7.3393 8.

i = 11 y = 8.5293 7.3393 8.8921 8.

In most cases, the array of values specified in the first line of the 'For' Loop is a

row vector i.e. a 1 ×n array. However, it can be an m ×n array in which case the loop

variable is initially assigned the first column of the array for the first iteration of the loop,

the second column of the array for the second iteration, etc. As an illustration, Example

13.1.6 can be modified to leave the array of values 'indices' as a single column vector

instead of transposing it into a row vector.

Example 13.1.

clear all

X=10*rand(4) % Create 4 ×× 4 array X of 16 random numbers from 0 to 10 indices=find(X>7) % Find indices of X corresponding to elements % greater than 7 and store as column vector for i=indices % Set loop variable i equal to column vector 'indices' i,y=X(i) % Address elements of X according to contents of column % vector i and store those elements in vector y end

X =

indices = 2 4 5 7 11

i = 2 4 5 7 11

y =

'For' Loops can be nested when appropriate.

Example 13.1.

A(4,4)=0 % Preallocate memory for array A for i=1: for j = 1: A(i,j)=(-1)^(i+j); % Create matrix 'A' of 1's and (-1)'s end % for j end % for i A B=(A+1)/2 % Create matrix B of 0's and 1's find(B) % Find indices of nonzero elements of array B

A =

B =

ans = 1 3 6 8 9 11 14 16

The power of MATLAB is its ability to treat arrays as a data type which can be

manipulated without the need for one or more nested loops. For example, if 'A' and 'B'

are equally sized arrays, then the matrix sum is simply 'A+B'. Other programming

13.2 While Loops

'While' Loops as the name suggests are a series of commands which are

repeatedly executed as long as some condition remains True. The syntax for a 'While'

Loop is

while expression

(commands)

end

Assuming the initial evaluation of the expression is True entering the 'While'

Loop, execution of the commands inside the loop eventually causes the expression to

become False. Otherwise, the loop would execute indefinitely. The expression can

produce either a scalar or an array. In either case, the single element or all the array

elements must be True for the loop commands to be executed. The primary difference

between the 'While' and 'For' Loops is the uncertainity about the number of loop

iterations in a 'While' Loop in contrast to the 'For' Loop which executes a fixed number

of times (assuming no 'break' command inside the 'For' loop).

Example 13.2.

x=0; hold on while cos(x)>sin(x) % Loop executes as long as cos(x)>sin(x) is True diff=cos(x)-sin(x); plot(x,diff,'r*') % Plot data point (x,diff) as a red * marker xlabel('x (rad)') ylabel('cos(x)-sin(x)') x=x+pi/100; % Increment x end % while cos(x)>sin(x) x,cos(x),sin(x) % Display last values of x, cos(x) and sin(x)

x = 0. ans = 0. ans = 0.

0 0. 1 0. 2 0. 3 0. 4 0. 5 0. 6 0. 7 0. 8

0

  1. 1

  2. 2

  3. 3

  4. 4

  5. 5

  6. 6

  7. 7

  8. 8

  9. 9

1

x ( r a d )

cos(x)-sin(x)

The 'While' Loop may fail to execute even once if the initial evaluation of the

test expression is not True. This can be avoided if necessary, i.e. there will be at least one

pass through the 'While' Loop commands, by initializing certain variables to guarantee

the initial evaluation of the test expressio n is True. In the following example, all

elements of the array 'y' are set to 1 to force the loop to execute at least once.

Example 13.2.

y=ones(1,5) % Initialize row vector y to all 1's sum=zeros(1,5); % Initialize row vector 'sum' to all 0's while y>0 % Continue loop execution while all elements of array y are % greater than zero x=randn(1,5) % Generate row vector x of N(0,1) values y=x+2 % Calculate array y values used in the 'while' expression sum=sum+x; end % while sum

y = 1 1 1 1 1

x = -0.8468 -0.2463 0.6630 -0.8542 -1. y = 1.1532 1.7537 2.6630 1.1458 0.

x = -0.1199 -0.0653 0.4853 -0.5955 -0. y = 1.8801 1.9347 2.4853 1.4045 1.

Example 13.2.

clear winnings=0; roster=char('Smith', 'Jones', 'Pierce', 'Edwards', 'Gonzalez', 'Bishop', 'Ball', 'Freeman', 'Lane', 'Price'); player=roster(1,:); k=0; while player(1)~='P'

k=k+1; index=ceil(10*rand) winnings(k)=0; for i=1:index winnings(k)=winnings(k)+10; if winnings(k)== break end % if winnings== end % for i player=roster(index,:)

end % while player(1)~='P' winnings

index = 2 player = Jones

index = 8 player = Freeman

index = 8 player = Freeman

index = 3 player = Pierce

winnings = 20 50 50 30

13.3 If-Else-End Constructions

There are times when a sequence of commands are to be executed only when a

relational condition evaluates as True. When its not, the commands are skipped. The

basic construct is

If expression

(commands)

end

The expression may be a simple logical expression or may consist of several

logical subexpressions.

Example 13.3.

format bank n=5; mu=65; sigma=15; student_ave=mu+sigma*randn(1,n); % Generate n N(mu,sigma) averages

for k=1:n student_grade(k,1:4)='Fail'; % Initialize kth student grade to Fail

if student_ave(k)>65 % Check if kth student ave greater than 65 student_grade(k,1:4)='Pass'; % Change kth student grade to Pass % if ave greater than 65 end % if student_ave(k)>

student_ave(k),student_grade(k,1:4) end % for k format short

ans = 58. ans = Fail

ans = 40. ans = Fail

ans = 66. ans = Pass

ans = 69. ans = Pass

ans = 47. ans = Fail

n = 1000 num_expected = 998 num_outliers = 2

When there are more than two alternatives, the correct syntax is

if expression

(commands evaluated if expression1 is True)

elseif expression

(commands evaluated if expression2 is True)

elseif expression

(commands evaluated if expression3 is True)

elseif ...

else

(commands evaluated if no other expression is True)

end

As soon as a True expression is encountered, the appropriate commands are

executed and control passes to the first command after the 'end' statement. Note, the

final 'else' is optional.

Example 13.3.

n=1000; mu=0; sigma=5; x=mu+sigmarandn(1,n); % Generate n N(mu,sigma) random deviates num_1_sigma=0; % Initialize number of outcomes within 1 sigma limits num_2_sigma=0; % Initialize number of outcomes within 2 sigma limits num_3_sigma=0; % Initialize number of outcomes within 3 sigma limits num_outliers=0; % Initialize number of outcomes outside 3 sigma limits for i=1:n if abs(x(i))<mu+1sigma % Check if x(i) is within 1 sigma limits num_1_sigma=num_1_sigma+1; % If so, Increment num_1_sigma elseif abs(x(i))<mu+2sigma %Check if x(i) within 2 sigma limits num_2_sigma=num_2_sigma+1; % If so, Increment num_2_sigma elseif abs(x(i))<mu+3sigma %Check if x(i) within 3 sigma limits num_3_sigma=num_3_sigma+1; % If so, Increment num_3_sigma else % x(i) is an outlier num_outliers=num_outliers+1; % Increment num_outliers end % if abs(x(i))<mu+1*sigma end % for i n,num_1_sigma,num_2_sigma,num_3_sigma,num_outliers

n = 1000 num_1_sigma = 689 num_2_sigma = 257 num_3_sigma = 53 num_outliers = 1

13.4 Switch_Case Constructions

When the choice of which sequence of commands to execute depends on an

equality test involving a common expression, a 'Switch-Case' construct is sometimes

easier to formulate. The syntax is

switch expression

case test_expression

(commands1)

case test_expression

(commands2)

case test_expressionN

(commandsN)

otherwise

(commands)

end

When 'expression' on the header 'switch' line is a scalar, it is compared with

'test_expression1', i.e. Is 'expression==test_expression1' True? If it

is, the sequence of commands in 'commands1' are executed. If its not, the process is

continued until a 'case' is encountered where it is True and the corresponding

commands are executed. If there is no 'case' where the 'expression' and

'test_expression' are equal, the commands after the optional 'otherwise' are

executed. Note, without the optional 'otherwise' present, its possible for none of the

alternative sequence of commands to be executed.

Example 13.4.

clear n=4; % Car loan duration in years m=12*n; % Car loan duration in months P=30000; % Loan amount

switch n

case 3 r=4.5; % Annual interest rate for 3 year car loan i=r/1200; % Monthly interest rate (as a decimal value) fact=(1+i)^m; A=P(ifact/(fact-1)); % Monthly payment for a 3 year car loan

case 'NBA Basketball' ave_salary=2250000; num_teams=24; num_players=12; league_payroll=ave_salarynum_teamsnum_players;

case 'NHL Hockey' ave_salary=750000; num_teams=18; num_players=20; league_payroll=ave_salarynum_teamsnum_players;

otherwise disp('No data available for this sport')

end % switch sport

if league_payroll> sport,league_payroll end % if league_payroll>

No data available for this sport