MATLAB
Examples of Iterative operations
Ch E 111
David A. Rockstraw, Ph.D., P.E.
New Mexico State University
Chemical Engineering Department
Nested Loop Statements
% Nested loops
for i=1:4
for j=1:3
disp([i j i*j])
end
end
Nested Loop Statements
clear A
for i=1:n
for j=1:n
if i j
A(i,j)=0;
else
A(i,j)=1;
end
end
end
A
Nested Loop Statements
clear A
for i=1:n
for j=1:n
if i j
A(i,j)=0;
else
A(i,j)=1;
end
end compare with the built-in function statement:
end
A AA=eye(n)-triu(ones(n),1)
Example 1
• Write a for loop which calculates the sum the
integers from 1 to 100 and the sum of the
squares of the integers from 1 to 100.
• Print out only the results.
Example 1 Solution
sum1 = 0;
sum2 = 0;
for i = 1:100
sum1 = sum1 + i;
sum2 = sum2 + i^2;
end
sum1
sum2
Example 2
• Determine the largest value of n such that
n
i 1
i 10
2 6
Example 2 Solution
sum = 0;
i = 0;
while ( sum tol)
n=n+1;
y=y+1/(n*n);
disp(sprintf('%g%s%g%s%g',n,' ',y,'
',aim-y))
end
grcodi script
• Write a program that, given two positive integers N1 and N2,
calculates their greatest common divisor. The greatest
common divisor can be calculated easily by iteratively
replacing the largest of the two numbers by the difference of
the two numbers until the smallest of the two numbers reaches
zero. When the smallest number becomes zero, the other gives
the greatest common divisor.
• You will need to use a while loop and an if-else statement. The
largest of two numbers can be obtained using the built-in
function MAX(A,B). The smallest of two numbers can be
obtained using the built-in function MIN(A,B).
grcodi script
% GRCODI - determine greatest common divisor
N1=input('first number = ');
N2=input('second number = ');
while (min(N1,N2)>0)
if (N1 > N2)
N1=N1-N2;
else
N2=N2-N1;
end
end
disp(sprintf('%s%g','GCD is ',max(N1,N2)))