You are on page 1of 11

1

Name:

Date:

Section:

Score:

WORKSHEET

Looping in MATLAB

Instructions: This shall serve as your proof of attendance for this meeting. Write what is asked of you on
the space provided beside each item.
Enter the following code on your Editor Window. Run the program:

for k = 1:5, disp(k); end


Formulate a problem whose answer is the code given above.

Do the same for each of the codes below:


Code 1
for k = linspace(0,2*pi,9), disp([k sin(k)]); end
Code 2
for k = 0:N-1, disp(N-k); end
Code 3
N = 10;
for j = 1:N
N = N - 1;
disp(j);
end
Code 4
X = zeros(5);
for k = 1:5
for j = 1:5
X(k,j) = (-1)^(k+j);
end
end
disp(X);
Code 1:
Code 2:
Code 3:
Code 4:

2
Problem statements and the code associated with each problem are given below. Each of the codes,
however, contains either syntax and/or a logical error, hence providing an answer that is erroneous.
Encircle the error, and provide the necessary corrections in the code in the space provided.
Problem 1
Write a program that will display the word Loading on the screen. For every second, a dot appears beside
the word. After three dots appear, the screen clears and displays the word Loading again without any
dots. Repeat this operation ten times.
Code:
for k = 1:10
fprintf('Loading.);
for j = 1:3
pause(1);
fprintf('.');
end
end

Corrections for Problem 1:

Write a program that will display the following number pyramid:


1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
Code:
R = 6; n = 1;
for r = 1:R
for c = 1:r
fprintf(' %d',c);
c = c + 1;
end
fprintf(' ');
end
Corrections for Problem 2:

Enter the following code on your Editor Window. Run the program:
res = 1;
while res == 1
str = input('Do you want to continue? (y/n): ', 's');
if str == 'y', res = 1;
else res = 0;
end
end
Formulate a problem whose answer is the aforementioned code.

3
Do the same for each of the codes below.
Code 1
G = ceil(rand*10);
trial = input('Guess the number: ');
while G ~= trial
disp('Try again.');
trial = input('Guess the number: ');
end
disp('You guessed correctly!');
Code 2
x = input('Give an integer: ');
k=0;
sum = 0;
while k~=x
k = k+1;
sum = sum+k;
end
disp(sum)
Code 1:
Code 2:

A problem statement and the code associated with it are given below. The code, however, contains either
syntax and/or a logical error, hence providing an answer that is erroneous. Encircle the error, and provide
the necessary corrections in the code in the space provided.
Problem
Suppose we have invested some money which draws 10 percent interest per year, compounded. We would
like to know how long it takes for the investment to double. More specifically, we want a statement of the
account each year, until the balance has doubled. Write a program that will be able to do this, with a
starting amount of Php 1000.
Code:
a = 1000;
r = 0.1;
bal = a;
year = 1;
fprintf('Year\tBalance');
while bal > 2 * a
bal = bal + r * bal;
fprintf('%g\t\t%g', year, bal);
end
Corrections for Problem:

MODULE 6

Looping in MATLAB

OBJECTIVE
At the end of this module, you should be able to:
1. Create programs using for and while statements in MATLAB
2. Apply pre-allocation of vectors and/or matrices in MATLAB programs

Looping in MATLAB
Looping in MATLAB simply means the repetition of statements and commands. Such repetition of
tasks is important in programs which require repeated application of a certain algorithm, in order to arrive
at a more accurate answer/result. In MATLAB, we have two kinds of looping statements:
1. Counted loops: these are loops that repeat statements for a specified number of times. Such loops
2.

use for statements.


Conditional loops: these are loops that repeat statements indefinitely. The repetition only stops
when a condition is met. Such loops use while statements.

for STATEMENTS
The for statement in MATLAB allows you to create programs that use counted loops, or loops that
repeat for a definite number of times.
We usually use the term iterate to signify the repetition of a certain task or command. We also use the
term iteration variable, which refers to the variable used to iterate through all the values. MATLAB has
built-in indices that can be used as iteration variables. For this module, we use the indexing variable "i".
As a warning for your future programs, avoid using "i" as a variable name for your other values.
The syntax for a for statement is:
for iter_var = range
action
end
The variable iter_var refers to your iteration variable, which may be any variable. However, for
simplicity and elegance of code, it is recommended that you either use i or j. Range refers to a series
of integers, written in the colon notation. This signifies how many times you need to repeat your action
statement.
As an example, if you want to print a row of numbers from 1 to 10 using the for statement, you may have
the code in the next page:

5
clc
clear
for i = 1:10
fprintf('%d ', i);
end
In a nutshell, what the code above exactly means is that the program will loop the values of i from 1 to 10.
At every loop, it executes the action statement, which is to display the value of i. It ends when the value of
i reaches 10. Notice that you can also carry out the same task by simply writing [1:10] in your Editor
Window, then running it afterwards.
Some programs may use the iteration variable in its action statements (in this case, the program above
displays its value). Most programs, though, usually just use it to count the number of times the action
statements have repeated themselves.
If you were to display a column of numbers from 1 to 10 using a for statement, you may have the following
code:
clc
clear
for i = 1:10
fprintf('%d\n', i);
end
Removing the space after the placeholder and changing it with a formatting command \n allows the display
of the iteration variables values on a new line.

A running variable is a common technique programmers use when carrying out looping statements. A
running variable is one that updates its value for every loop. Consider the following problem: Write a
program that calculates the sum of the first 15 positive integers.
The code for the program may look like the following:
clc
clear
n = 15;
i = 1;
rsum = 0;
for i = 1:n
rsum = rsum + i;
end
disp(rsum);
The running variable for this program is rsum, which stands for running sum. The running sum variable
keeps changing its value for every loop; in fact, we continually add a new value to its previous value.
At the start of the program, it is necessary that we first set the value of the running variable rsum to zero, to
avoid adapting its previous value. Once the loop starts its first iteration, rsum updates itself by using an

6
overwriting assignment. The previous value has been added to the current value of i, and will continue
doing so until the iteration variable reaches a value of 15 (initially assigned before the looping started). The
program then outputs the result.
The same programming technique can be applied when one wants to calculate the factorial of n. For
example, if you want to determine the factorial of 15, the following code may work:
clc
clear
n = 15;
i = 1;
rprod = 1;
for i = 1:n
rprod = rprod*i;
end
disp(rprod);
Note that, in this case, the initial value for the running product variable rprod is 1, instead of 0.

By using the length() function of MATLAB with the for statement, you can also determine the total
sum of all the elements of a vector (or a matrix). The length() command outputs the number of
elements a vector has. If you already know how many elements there are in a given vector, then you can
loop from the first until the last element of the vector. For example:
vector = [1 3 5 7 9];
sumv = 0;
for i = 1:length(vector)
sumv = sumv + vector(i);
end
disp(sumv)
The program above uses the variable sumv to store the value of the running sum for every loop. The for
statement loops from 1 until 5, which is the length of the variable vector. For every loop, the running
sum is updated by adding the value of vector(i), which refers to the ith element of vector. Note that
i changes its value for every loop.
The same algorithm can also be applied one wants to find the product of all elements in a vector. In this
case, the initial value changes from 0 to 1.
Try to search also how the functions sum and prod work.

LOOPS WITH CONDITIONAL STATEMENTS


MATLABs conditional statements (if, if-else, elseif) can also be integrated as action
statements in a loop. This simply means that for every loop the program does, MATLAB decides
whether to further carry out an action or not.

7
As an example: For a given vector with n elements, create a program that identifies the element with the
minimum value. Since this is looping through all the elements of a vector, the commands length() and
vector(i) will be most useful. As a hint: assume that the first element is the minimum value.
Your code may look like this:
vector = [1 3 5 7 9];
minv = vector(1);
for i = 2:length(vector)
if vector(i) < minv
minv = vector(i);
end
end
disp(minv);
The program assumes that the first value is the minimum. The program then starts looping from the
second element up to the final element of the vector. If the vector element inside the loop is less than the
previous minimum value, then the program changes the value of the minimum. This decision-making is
applied as MATLAB loops through every element of the vector.
Will this algorithm still work if one wants to find the maximum value in a vector? How would the code
change?

NESTED for LOOPS


Nested statements mean that one uses a command as an action statement of that same command. Nested
for loops occur when the action of a for loop is another for loop.
As an illustration: create a program that prints a box of asterisks. The user must be prompted for the
number of columns (m) and rows (n). As a hint: Begin the program by looping by row. For every row, you
have to print n number of stars (looping by column).
You may have the following code:
clc
clear
row = input('Enter number of rows: ');
column = input('Enter number of columns: ');
for i = 1:row
for j = 1:column
fprintf('*');
end
fprintf('\n');
end
The program starts by prompting the user for the dimensions of the box of asterisks (number of rows and
columns). The program starts by looping through every row. For the first row, MATLAB also loops
through every column, displaying the asterisk symbol from the first column until the specified number of
columns by the user. After looping through all the columns, the program then creates a new line, and once

8
again, MATLAB loops through another row, until it reaches the final number of rows specified by the
user.

EXERCISE FOR for STATEMENTS


1.

As an exercise, recall the Rock-Paper-Scissors game from the previous module. Simulate this game
again, but this time:
a. Prompt the user for the desired number of rounds
b. Record the scores of the players (user vs. MATLAB) for every round
c. At the end of the game, display the winner and the score

2.

Write a program that will prompt the user for a maximum Celsius value in the range from -16 to 20.
Then, print a table showing degrees F and degrees C until this maximum value is reached. Use a for
statement.
a. First value that exceeds the maximum should not be printed.
b. The table should start at 0 degrees F, and increment by 5 degrees F until the maximum (in C)
is reached.
c. Both temperature scales should be printed.
d. Use only one decimal place.
As a sample output:
Enter a maximum temperature from -16 to 20 degrees Celsius: 9
F
0.0
5.0
10.0
15.0
20.0
25.0
30.0
35.0
40.0
45.0

C
-17.8
-15.0
-12.2
-9.4
-6.7
-3.9
-1.1
1.7
4.4
7.2

while STATEMENTS
The while statement allows conditional looping in MATLAB. Conditional looping refers to repeating
an action indefinitely; the repetition only stops when a condition is met/becomes true.
The syntax for a while statement is:
while condition
action
end
The condition is always written as a logical expression. The action statement/s is/are executed as long as
the condition is true. When the condition becomes false, the looping stops, and the program ends. One

9
must be very cautious in creating logical expressions: the condition must be such that it can be false (hence,
the program can end). Otherwise, an infinite loop occurs. The program will have no way to end itself,
unless the user manually terminates it by using Ctrl-C.
As an example: Create a program that will find the last integer n for which n! less than a 100-digit number.
Some hints:
1. Start by initializing all variables to 1.
2. Loop until the factorial value reaches 110100 (101-digit number).
Your program may look like this:
clc
n = 1;
nfactorial = 1;
while nfactorial < 1E100
n = n + 1;
nfactorial = nfactorial * n;
end
disp(n-1);
As long as the variable nfactorial is still less than 110100, the program loops, and updates the value of
the running product variable nfactorial. Take note that n increases its value by 1 for every loop as well,
making the factorial operation possible. Once nfactorial becomes greater than 110100, the condition
becomes false, and the looping stops. The program then displays n-1 as the answer (why is this so?).
Another example: Prompt the user for an integer. When a positive number is given, the program echoprints the number, and asks for another. When a negative number is given, the program will display the
negative number, and end.
Your code may look like this:
clc
clear
number = input('Enter integer: ');
while number > 0
fprintf('Your number is %d.\n', number);
number = input('Enter another integer: ');
end
fprintf('Your number is %d. It is negative. Thank you!\n', number);

ERROR-CHECKING
One application of the while statement is error-checking: when the user input is not within the
range/guidelines specified by the problem, the program displays an error message, and asks for another
input. This scheme is repeated until a correct input is given.
As an example: From the previous for statement exercise, write a program that will prompt the user for a
maximum Celsius value in the range from -16 to 20. Then, print a table showing degrees F and degrees C
until this maximum value is reached. Use a for statement. Insert an error-checking scheme so that when
the user inputs a value outside the given range, the program will ask for another value. As a hint: start the

10
program with a conditional looping. Until the user inputs a value within the range, the program will
continually prompt the user for another input. Carry out all other operations after this loop.
Your program code may look like this:
clc
clear
maxtemp = input('Enter maximum temp: ');
while maxtemp < -16 || maxtemp > 20
fprintf('\nInput error! Value not within range.\n');
maxtemp = input('Enter another maximum temp: ');
end
degf = (maxtemp*1.8)+32;
fprintf(' F
C\n');
for i = 0:5:degf
degc = (i-32)*(5/9);
fprintf('%4.1f\t%.1f\n', i, degc);
end
Notice that we can use both for and while statements to do different tasks for a single program.

EXERCISE FOR while STATEMENTS


1.

Write a program that will calculate the average of a class by prompting the user for the individual
grades of the students. The program will continuously ask the user for the individual grades until he
inputs -1, in which case the looping will stop. The program will then display the total number of
students, and the class average.

2.

Consider again item # 1: What if the program will also display the highest and lowest grades?

3.

Transform the Rock-Paper-Scissors game into a Jack-En-Poy simulation:


a. Prompt the user for the maximum score desired.
b. The program has to score every round.
c. The first player to reach maximum score is declared the winner.

VECTOR/MATRIX PRE-ALLOCATION
To pre-allocate in MATLAB is to initially set the dimensions of a vector/matrix before looping starts.
Programmers pre-allocate arrays in order to improve the speed of program execution.
As an example: You are given a row vector A containing 100,000 positive integers, whose values could
range from 1 to 5. You can generate row vector A using the following command:
A =
ceil(rand(1,100000)*5). The program is to generate another row vector B that contains the
cumulative sum corresponding to each element of A.
To illustrate the execution of this program, if row vector A contains [1 2 3 4] as elements, then the
program should display row vector B as [1 3 6 10].

11
Your program code may look like the one given in the next page:
clc
clear
tic;
A = ceil(rand(1,100000)*5);
b(1) = A(1);
for i = 2:length(A)
b(i) = b(i-1) + A(i);
end
toc;
The tic-toc function is inserted before the loop command so that MATLAB can time the entire
operation. The first element of vector b is vector As first element. The next elements, though, are
cumulative sums of the previous elements of A. Hence, the second element of b is the sum of As first and
second element. This scheme is repeated until all of the elements of A have been passed. The total running
time for the execution of this program is 29.8 seconds. Note that this can change, and depends on the
computing speed of your computer.
Now, consider the following code, which implements pre-allocation:
clc
clear
tic;
A = ceil(rand(1,100000)*5);
b = zeros(1,100000);
b(1) = A(1);
for i = 2:length(A)
b(i) = b(i-1) + A(i);
end
toc;
The code above adds an additional line: b = zeros(1,100000). This line sets the length of vector b to
100000. It also sets the contents of b to zeroes. This is fine; the looping command following this line
overwrites the values. The total time for the code above to execute is 0.006 seconds, almost 5000 times
faster than the previous one!
For the first set of codes, MATLAB generates a new vector (for each loop) larger than the previous one.
This consumes memory and storage space, hence the longer execution time. On the other hand, the second
set of codes already created a vector for b, and for every loop MATLAB no longer needs to generate a new
vector. This reduces the memory and storage use, and results to a faster execution time.

You might also like