MATLAB - While Loop
MATLAB - The while Loop
Section titled “MATLAB - The 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.
Syntax
Section titled “Syntax”The basic syntax of a while loop in MATLAB is:
while <condition> % Code block to be executed <statements>endThe loop operates as follows:
- MATLAB first evaluates the
<condition>. - If the condition is
true, the<statements>inside the loop body are executed. - After execution, the control returns to step 1.
- If the condition is
false, the loop terminates, and the program continues with the statement immediately following theendkeyword.
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.
Example: A Simple Counter
Section titled “Example: A Simple Counter”Let’s create a script file to demonstrate a basic while loop that counts from 10 up to 19.
% Initialize the counter variablea = 10;
% The while loop continues as long as 'a' is less than 20while (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: 10Value of a: 11Value of a: 12Value of a: 13Value of a: 14Value of a: 15Value of a: 16Value of a: 17Value of a: 18Value of a: 19Loop finished. Final value of a is 20Controlling Loop Execution
Section titled “Controlling Loop Execution”You can control the flow of a while loop using the break and continue statements.
break: Immediately terminates the entirewhileloop.continue: Skips the rest of the current iteration and proceeds to the next evaluation of the loop’s condition.
Example with break and continue
Section titled “Example with break and continue”% Find the first multiple of 7 greater than 50num = 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 loopendCommon Pitfalls & Best Practices
Section titled “Common Pitfalls & Best Practices”- Infinite Loops: The most common error is forgetting to update the variable that controls the loop condition. This causes the condition to remain
trueforever. Always ensure your loop’s logic allows the condition to eventually becomefalse. forvs.while: Use aforloop when you know the exact number of iterations (e.g., iterating over elements of a vector). Use awhileloop 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