0
0
MATLABdata~5 mins

While loops in MATLAB

Choose your learning style9 modes available
Introduction

A while loop repeats a set of instructions as long as a condition is true. It helps automate tasks that need to happen multiple times without writing the same code again and again.

When you want to keep asking a user for input until they give a valid answer.
When you want to repeat a calculation until the result is close enough to a target.
When you want to process data until there is no more data left.
When you want to keep running a game loop until the player quits.
Syntax
MATLAB
while condition
    % commands to repeat
end
The condition is checked before each repetition. If it is true, the commands inside run.
Make sure the condition will become false at some point, or the loop will run forever.
Examples
This loop prints numbers from 1 to 5. It stops when count becomes 6.
MATLAB
count = 1;
while count <= 5
    disp(count)
    count = count + 1;
end
This loop prints 10, 8, 6, 4, 2. It decreases x by 2 each time until x is no longer greater than 0.
MATLAB
x = 10;
while x > 0
    disp(x)
    x = x - 2;
end
Sample Program

This program prints a greeting three times, showing the current number each time.

MATLAB
n = 1;
while n <= 3
    fprintf('Hello number %d!\n', n);
    n = n + 1;
end
OutputSuccess
Important Notes

Always update variables inside the loop that affect the condition to avoid infinite loops.

You can use break inside a while loop to exit early if needed.

Summary

While loops repeat code as long as a condition is true.

Check and update the condition inside the loop to stop it eventually.

Useful for repeating tasks when you don't know in advance how many times they will run.