MATLAB Looping
Mechanisms (Part 1)
Mr. Christopher Winfrey
Fall 2022
What is a Loop?
❖ We discussed basic conditional statements like IF-ELSE IF-
ELSE statements and SWITCH CASE statements
❖ We can consider loops to be a more complex conditional
statement
❖ A loop is something (like an algorithm) that will repeat
❖ Something is needed to keep the loop going or to break out
of it.
What are Looping Mechanisms?
❖ A code that repeats several times depending on
some starting condition that is re-checked each time
the code is repeated.
❖ We will focus on two main types of loops in
MATLAB
❖ WHILE Loops – Loops (repeats) WHILE the
condition remains true
❖ FOR Loops – Loops (repeats) FOR a certain
number of iterations
While Loop Example
❖ WHILE Loop – Loops as long as the starting condition remains true
❖ After each loop, the condition is checked again
❖ Once the condition becomes false, the loop is not processed any further.
❖ Example:
a = 10;
while( a < 20 )
sprintf('value of a: %d\n', a);
a = a + 1;
end
❖ If we try to follow this program…
❖ ‘a’ begins with a value of 10.
❖ The while loop checks if ‘a’ is less than 20 (which is true because 10 < 20).
❖ Therefore, it prints out the value of ‘a’ and then adds 1 to the value of ‘a’.
❖ Then, the loop repeats, and it checks if ‘a’ (which is now 11) is less than 20.
❖ This repeats until ‘a’ is equal to 20.
FOR Loop Example
❖ FOR Loop – Loops for a specific number of times
❖ Keeps track of each iteration (or how many times the loop has been processed)
❖ Index variable increments with each loop
❖ Example:
sum = 0
for n = 1:6
sum = sum + n
end
❖ Image following this code…
❖ You start with a value of 0 in the variable “sum”
❖ The loop assigns a value of 1 to “n” on the first iteration and adds that value to sum.
❖ The loop then repeats, but now “n” becomes two and is added to the sum.
❖ This repeats until “n” becomes 6 and is added to the sum.
Exercises
These exercises are NOT your
homework assignment. These are
not required. However, they are
meant to help with your
understanding of concepts!
Exercise 1 – While Loop
% Note that a percent symbol represents a comment in code, so it won’t be run like code
% This code calculates 10! (or 10 factorial).
n = 10;
f = n;
while n > 1 % Loop while n is greater than 1
n = n - 1; % Decrease the value of n by 1
f = f * n; % Multiply the value of f by the value of n
end
Exercise 2 – For Loop
% Note that a percent symbol represents a comment in code, so it won’t be run like code
for x = 1:10 % Loop, where each loop changes the value of x (10 times)
fprintf('value of x: %d\n', x); % Print the value of x for this loop iteration
end % End of your FOR loop