Sometimes you need to repeat code until a specific condition changes, but you do not know in advance how many iterations that will take. For example, suppose you want to double a number until it exceeds 1000:
num = 1;
num = num * 2; % 2
num = num * 2; % 4
num = num * 2; % 8
num = num * 2; % 16
num = num * 2; % 32
num = num * 2; % 64
num = num * 2; % 128
num = num * 2; % 256
num = num * 2; % 512
num = num * 2; % 1024
fprintf('Final value: %i\n', num)
num = 1;
while num <= 1000
num = num * 2;
end
fprintf('Final value: %i\n', num)
The loop version automatically stops when num exceeds 1000. Without a loop, you must manually count iterations and hope you wrote enough (or not too many) doubling operations. If you change the starting value or the threshold, the loop still works without modification, but the explicit version would need rewriting.
A good way to understand a while-loop is to think of it as a repeating if-statement. It checks the condition, runs the code if true, then checks again, and so on until the condition becomes false.
MATLAB repeatedly executes code_block as long as loop_condition evaluates to true. Think of it like an if-statement that jumps back to the top and checks the condition again.