Next: Selective Indexing Up: Flow Previous: Relations

### Control

You can do normal programming things in MATLAB. The explicit looping operators are while and for. The syntax of while is

while relation
statements
end

The indentation is customary but not required. As long as relation holds true, statements will be executed repeatedly. The end is mandatory. When relation evaluates to False (0), execution resumes after end.

for variable = matrix
statements
end

causes variable to assume the value of each column of matrix in succession, and execute statements for each, then resume after the mandatory end. Frequently matrix will be a vector, e.g.
for n = 1:5
will run n from 1 to 5.

If MATLAB encounters the command break inside a for or while loop, it immediately jumps to the end. If there are nested loops, only the innermost is broken out of.

Conditional control and branching are accomplished with if, whose most general syntax is

if relation
statements
elseif another relation
more statements
elseif a third relation
a third set of statements
else
last statements
end

There can be any number of elseifs, and the final else is optional; the end is mandatory as usual. The first relation of an if or elseif that evaluates to True (anything non-zero) is used; its statements are executed and control then passes to after the end. If no relation is True, the else statements, if any, are executed.

All control structures can be nested. Control structures are relatively slow and inefficient in MATLAB; what MATLAB is good at is matrices. Instead of applying for over a vector, you can usually apply your function(s) to the vector directly so it operates element-wise; this will be much faster. Instead of for with if, to test over the elements of a vector, you can and should use selective indexing (see below).

Next: Selective Indexing Up: Flow Previous: Relations

sepherke
Sat Mar 21 21:42:28 EST 1998