statement - Branches
statement evaluates a logical expression and executes a group of
statements when the expression is true.
The optional elseif
keywords provide for the execution of alternate groups of statements.
keyword, which matches the if,
terminates the last group of statements.
This type of structure is also known as branches or 'branching'.
The groups of statements are delineated by the four keywords (no braces
brackets are involved).
The general form
of the statement is:
It is important to understand how relational
operators and if
statements work with matrices.
When you want to check for equality between two variables, you might
use if A == B ...
This '==' code is fine, and it does what you expect when A and B are scalars.
But when A
and B are matrices,
A == B does not test if they are equal, it tests where they
equal; the result is another matrix of 0’s and 1’s showing
In fact, if A
and B are not the same size,
then A == B is an error.
The proper way to check for equality between two variables is to use the
Here's an example code:
becomes 3, and the routine continues after the end.
If not, the routine tests if abs(m-n) equals 3. If
it does, then a(m,n)
becomes 1, and the routine continues after the end.
In any other case a(m,n)
becomes 0, and the routine continues after the end.
Several functions are helpful for reducing the results of matrix
comparisons to scalar conditions for use with if, including:
'if statement' to
to 'Matlab Code'