BIL113E - Introduction To Scientific and Engineering Computing (MATLAB)
BIL113E - Introduction To Scientific and Engineering Computing (MATLAB)
1-3
for-end loops
In for-end loops the execution of a command, or a group of
commands, is repeated a predetermined number of times. The
form of the loop is as follows:
for loop variable=first value:increment:last value
..... A group of
..... MATLAB commands
end
For example, if for i=1:2:9, there are five loops, and the value of
i in each loop is 1, 3, 5, 7, and 9
The loop index variable can have any variable name ( i, j, k,
counter...)
Each for command in a program must have an end command.
for-end loops
For example; let for i=a :b :c.
In the first iteration, i=a and the computer executes the commands
between the for and the end commands. Then, the program goes
back to the for command for the second iteration. i obtains a new
value equal to i=a+b, and the commands between the for and the
end commands are executed with the new value of i. The process
repeats itself until the last iteration where i=c. Then, the program
does not go back to the for, but continues with the commands
that follow the end command.
The increment b can be negative (i=25:–5:10 produces four
iterations with i= 25, 20, 15, 10). If the increment value is omitted,
the value is 1 (default) (i.e. for i=3:7 produces five iterations with
i= 3, 4, 5, 6, 7).
While-end loops
The form of the loop is as follows:
while conditional expression
..... A group of
..... MATLAB commands
end
while-end loops are used in situations when looping is needed
but the number of iterations is not known ahead of time. In
while-end loops the number of passes is not specified when the
looping process starts. Instead, the looping process continues until
a stated condition is satisfied.
The conditional expression in the while command must include
at least one variable.
While-end loops
The first line is a while statement that includes a conditional
expression. When the program reaches this line the conditional
expression is checked. If it is false (0), MATLAB skips to the end
statement and continues with the program. If the conditional
expression is true (1), MATLAB executes the group of commands
that follow between the while and end command. Then, MATLAB
jumps back to the while command and checks the conditional
expression. This looping process continues until the conditional
expression is false.
for-end / while-end loops
sum=0; i=1; sum=0;
for i=1:10 while i<=10
sum=sum+i; sum=sum+i;
end i=i+1;
fprintf('%d\n',sum); end
fprintf('%d\n',sum);
55
55
for i=1:2:10 i=1;
i=i^2; while i<=50
end i=i^2;
fprintf('%d\n',i); i=i+2;
end
81 fprintf('%d\n',i);
123
Write your name on the screen n times
(with for and while loops)
name=input('Enter name and surname ','s');
n=input('Number of times displayed on screen ');
for i=1:n
fprintf('%s\n',name);
end