Loop Control Statements - MATLAB & Simulink (original) (raw)

With loop control statements, you can repeatedly execute a block of code. There are two types of loops:

Each loop requires the end keyword.

It is a good idea to indent the loops for readability, especially when they are nested (that is, when one loop contains another loop):

A = zeros(5,100); for m = 1:5 for n = 1:100 A(m, n) = 1/(m + n - 1); end end

You can programmatically exit a loop using a break statement, or skip to the next iteration of a loop using a continue statement. For example, count the number of lines in the help for the magic function (that is, all comment lines until a blank line):

fid = fopen('magic.m','r'); count = 0; while ~feof(fid) line = fgetl(fid); if isempty(line) break elseif ~strncmp(line,'%',1) continue end count = count + 1; end fprintf('%d lines in MAGIC help\n',count); fclose(fid);

Tip

If you inadvertently create an infinite loop (a loop that never ends on its own), stop execution of the loop by pressing Ctrl+C.

See Also

for | while | break | continue | end

External Websites