I am writing an easy IF condition. The function is to judge each row of the matrix to be certain vectors. The code is as follows:
if (compareM(i,:)==[1, 0])||(compareM(i,:) ==[2, 1])
match_1 = match_1 +1;
else
mismatch_1 = mismatch_1 +1;
end
The error said ''Operands to the || and && operators must be convertible to logical scalar values''.
compareM is a n by 2 matrix and I wonder if the error is made by || operation. Thanks in advance!
If you are comparing vectors, not scalar values, you have to use |
operator. As a result you get logical vector of element-by-element pairwise comparison. To use it in IF statement you have to convert either each logical statement (then use ||
) or the result of |
the to scalar with ALL, ANY or other function.
If you want to compare to vectors for equality use ISEQUAL function as
if isequal(compareM(i,:)==[1, 0]) || isequal(compareM(i,:)==[2, 1])
compareM(i, :)
evaluates to a 1x2 numeric array, so compareM(i,:)==[1, 0]
evaluates to a 1x2 logical array. The same for the expression to the right of the ||
sign. But you need a single logical value on each side of ||
, not a 1x2 array of logical values.
If you want this expression to evaluate to true if both values on the lhs of ==
are the same as the corresponding elements on the rhs, wrap all()
around each side:
all(compareM(i,:)==[1, 0]) || all(compareM(i,:) ==[2, 1])
if ((compareM(i,:)==[1, 0])||(compareM(i,:) ==[2, 1]))
match_1 = match_1 +1;
else
mismatch_1 = mismatch_1 +1;
end
Note the outer enclosing parentheses.
if isequal(compareM(i,:), [1,0])
; right now you have a combination of the corrected version and the original - bnaul 2012-04-04 21:17