Skip to content

MATLAB - While Loop

A while loop is a fundamental control flow structure in MATLAB that repeatedly executes a block of code as long as a specified condition remains true. It is ideal for situations where the number of iterations is not known beforehand.

The basic syntax of a while loop in MATLAB is:

while <condition>
% Code block to be executed
<statements>
end

The loop operates as follows:

  1. MATLAB first evaluates the <condition>.
  2. If the condition is true, the <statements> inside the loop body are executed.
  3. After execution, the control returns to step 1.
  4. If the condition is false, the loop terminates, and the program continues with the statement immediately following the end keyword.

A condition is considered true if its result is a non-empty array containing all non-zero elements (logical or real numeric). Otherwise, the condition is false.

Let’s create a script file to demonstrate a basic while loop that counts from 10 up to 19.

% Initialize the counter variable
a = 10;
% The while loop continues as long as 'a' is less than 20
while (a < 20)
% Display the current value of 'a'
fprintf('Value of a: %d\n', a);
% IMPORTANT: Update the counter to avoid an infinite loop
a = a + 1;
end
fprintf('Loop finished. Final value of a is %d\n', a);

Running this script produces the following output:

Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15
Value of a: 16
Value of a: 17
Value of a: 18
Value of a: 19
Loop finished. Final value of a is 20

You can control the flow of a while loop using the break and continue statements.

  • break: Immediately terminates the entire while loop.
  • continue: Skips the rest of the current iteration and proceeds to the next evaluation of the loop’s condition.
% Find the first multiple of 7 greater than 50
num = 50;
while true % An intentionally infinite loop, controlled by break
num = num + 1;
% Skip if the number is not a multiple of 7
if mod(num, 7) ~= 0
continue;
end
% If we reach here, a multiple of 7 was found
fprintf('First multiple of 7 after 50 is: %d\n', num);
break; % Exit the loop
end
  • Infinite Loops: The most common error is forgetting to update the variable that controls the loop condition. This causes the condition to remain true forever. Always ensure your loop’s logic allows the condition to eventually become false.
  • for vs. while: Use a for loop when you know the exact number of iterations (e.g., iterating over elements of a vector). Use a while loop when you need to iterate until a specific condition is met (e.g., reading from a file until the end is reached, or running a convergence algorithm).

matlab_loops.htm