Command Sequence Controls

Syntax and Looping

The Syntax for for and while loops is as follows

for- loop syntax

for <variable> = <start>:<step>:<finish>

<commands>…..

……………..

end

while- loop syntax

while <condition>

<commands>…..%executed if condition is true

……………..

end

Example: for-loop versus while - loop

for i = 1:1:10

i=i+1 %***********

end

  • Note: the commandfor i=1:1:10’ does not create an array.
  • Note: the command ‘for i=1:1:10’ is equivalent to ‘for i=1:10’.

Now, let’s do the same by using while- loop

i=1; %we need to have a starting point to be able

to check the condition at the first time

while i<12 % to check is whether i<12 or not

i=i+1 %this command is the same as in for-loop

% we should get the next value of i

end

This way is a bit longer, so if you definitely know how many times you will need to do some commands, use for –loop. As you will see below, there are some situations, when using while-loop is the only way to solve the problem.

Example: (from a past MATLAB test)

> Calculate the sum S of elements ai =√2i-1, i=1, 2, ..., until the sum will exceed 20. Type in the following code and examine the output.

S=0; % Initial assignment for sum to be able to

% check condition

i=1; % first value for i is 1

while S<20 %condition to check

S=S+sqrt(2*i-1); % recurrent formula for S

i=i+1; % next i

end

number_of_loops=i-1 % do you know why i-1?

S % shows the final value

 

> Exercise: Understanding Looping

Type the above for- loop into MATLAB. How many times will the starred line of the previous example be executed? What are starting point, increment (step) and ending point of this loop?

Start:

Step:

End:

Total number of loops: