"end".
7.3.1 The for loop
If you want to repeat a certain commands in a
predetermined way, you can use the "for" loop. The
"for" loop around some statement, and you must tell
Matlab where to start and where to end. Basically,
you give a vector in the "for" statement, and Matlab
will loop through for each value in the vector:
for i = 1:n
for j = 1:n
a(i,j) = 1/(i+j );
end
end
Cont’d
Find summations of even numbers between 0
and 100
sum = 0;
for i = 0 : 2 : 100
sum = sum + i;
end
Cont’d
Cont’d
Example 2:- write a script file to compute the sum of the first 15 terms
in the series 5k2-2k, k=1,2,3,---,15.
Solution
Exercise
1) Assume n has a given value. Create the square matrix of n×n
elements, using a(i,j) =1/(i+j -1);
statements
end
MATLAB first tests the truth of the logical expression. A loop variable
must be included in the logical expression
Figure 7–3 Flowchart of the while loop.
Cont’d
Example 1:- A simple example of a while loop is
x = 5;
while x < 25
x = 2*x - 1;
disp(x)
end
The loop variable x is initially assigned the value 5, and it has this
value until the statement x = 2*x - 1 is encountered the rst time.
Cont’d
x=1;
while x < 10
x = x+1;
end
• The statements will be repeatedly
executed as long as the relation remains
true.
Cont’d
x=10;
while x > 1
x = x/2;
end
>>x=0.6250
• The condition is evaluated before the body is
executed, so it is possible to get zero iteration
when x equal to 1 or less.
Example
sum = 0;
x = 1;
while x < 4
sum = sum + 1/x;
x = x + 1;
end
>>sum
sum = 1.8333
Example 2
Write a script file to determine the number of terms required for
the sum of the series 5k2 -2k, k =1, 2, 3,---, to exceed 10 000.