In their basic forms, these MATLAB flow control statements operate like those in most computer languages. For example, the statement
for i = 1:n, x(i)=i^2, end
or
for i = 1:n
x(i) = i^2
end
will produce a certain n-vector, and the statement
for i = n:-1, x(i)=i^2, end
will produce the same vector in reverse order. The statements
for i = l:m
for j = l:n
H(i, j) = 1/(i+j-1);
end
end
H
will produce and print to the screen the m-by-n Hilbert matrix. The semicolon on the inner statement suppresses printing of unwanted intermediate results while the last H displays the final result.
The general form of a while loop is
while relation
statements
end
The statements will execute repeatedly as long as the relation remains true.
For example, for a given number a, the following will compute and display the smallest nonnegative integer n such that 2^n >= a:
n = 0;
while 2^n < a
n = n + 1;
end
n
The general form of an IF statement is illustrated by
if n < 0
x(n) = 0;
elseif rem(n,2) == 0
x(n) = 2;
else
x(n) = 1;
end
In two-way branching, the elseif portion would, of course, be omitted.
The relational operators in MATLAB are
< less than
> greater than
<= less than or equal
>= greater than or equal
== equal
~= not equal.
Note that "=" is used in an assignment statement while "==" is used in a relation.
Relations may be connected or quantified by the logical operators
& and
| or
~ not
When applied to scalars, a relation is actually the scalar 1 or 0, depending on whether the relation is true or false. Try 3 < 5, 3 > 5, 3 == 5, and 3 == 3. When applied to matrices of the same size, a relation is a matrix of 0's and 1's giving the value of the relation between corresponding entries. Try a = rand(5), b = triu(a), a == b.
A relation between matrices is interpreted by WHILE and IF to be true if each entry of the relation matrix is nonzero. Hence, if you wish to execute a statement when matrices A and B are equal you could type
if A == B
statement
end
but if you wish to execute the statement when A and B are not equal, you would type
if any(any(A ~= B))
statement
end
or, more simply,
if A == B else
statement
end
Note that the seemingly obvious
if A ~= B, statement, end
will not give what is intended, since this statement would execute only if each of the corresponding entries of A and B differs. You may use the any and and functions creatively to reduce matrix relations to vectors or scalars; two anys are required above, since any is a vector operator (see the section on "Matlab Vector Functions").
The FOR statement permits any matrix to be used instead of 1: n. See the MATLAB User's Guide for details of how this feature expands the power of the FOR statement.
Click on an item listed below to access additional MATLAB-related hints.
Return to ACS home page.
Please send comments and suggestions to
consult@rpi.edu