
Flow Control
It is important to unde rstand how relational operators and if statements
work with matrices. When you want to check for equality betwe en two
variables, you might use
ifA==B,...
This is valid MATLAB code, and does w hat you ex pe ct when A and B are
scalars. But when
A and B are matrices, A==Bdoes not test if they are
equal, it tests where they are equal; the result is another m atrix of 0’s and
1’s showing element-by-element equality. (In fact, if
A and B are not the same
size, then
A==Bis an error.)
A = magic(4); B = A; B(1,1) = 0;
A==B
ans =
0111
1111
1111
1111
The proper way to check for equality between two variables is to use the
isequal function:
if isequal(A, B), ...
isequal
returns a scalar logical value of 1 (representing true)or0 (false),
instead of a matrix, as the expression to be evaluated by the
if function.
Using the
A and B matrices from above, you get
isequal(A, B)
ans =
0
Here is another example to emphasize this point. If A an d B are scalars, the
following program will never reach the “unexpected situation”. But for most
pairs of matrices, including our magi c squares with interchanged columns,
none of the matrix conditions
A>B, A<B,orA==Bis true for all elemen ts
and so the
else clause is executed:
if A > B
'greater'
4-3
Comentarios a estos manuales