# Why two different ways of expressing the same logical condition lead to two different results ???

41 views (last 30 days)
Dung Le on 5 Jan 2016
Commented: Dung Le on 5 Jan 2016
I run two codes with a little difference in the way I express logical conditions, namely:
In code 1: I write : A(k,4) > B(:,2) & B(:,2)> A(k,3) In code 2: I write : A(k,4) > B(:,2) > A(k,3)
But in code 1 I have the expected result and in code 2, i do not.
Here are two full code I used:
Code 1:
for i=1:89 for j=1:64 for k=1:3 for h=1:2 mask = B(:,5) == A(i,1) & B(:,4) == A(j,2) & A(k,4) > B(:,2) & B(:,2)> A(k,3) & A(h,5) < B(:,1) < A(h,6);
end
end
end
end
xlswrite('panel.xlsx',B)
Code 2:
for i=1:89 for j=1:64 for k=1:3 for h=1:2 mask = B(:,5) == A(i,1) & B(:,4) == A(j,2) & A(k,4) > B(:,2) > A(k,3) & A(h,5) < B(:,1) < A(h,6);
end
end
end
end
xlswrite('panel.xlsx',B)
In order to see the difference in result, I save the output from code 1 into column 5, 6 and the output from code 2 into column 7, 8 both in file panel.xlsx.
Please run these two codes with two attached excel files and help me, thanks!

Stephen23 on 5 Jan 2016
The basic problem is that you are attempting two logical relations simultaneously: MATLAB's relational operators are binary operators, so they only support one comparison at once. In summary:
X<A<Y % is NOT valid for comparing A against X and Y
X<A & A<Y % This compares A with both X and Y
In MATLAB logical relational operators follow the standard rules of operator precedence. Look at this example carefully:
>> 3<4<2
ans =
1
The output is true, so does this mean that 4<2 ? Of course not, we just have to remember the operator precedence rules, just like in high school. This is evaluated according to those rules as:
>> (3<4)<2
ans =
1
where
>> 3<4
ans =
1
So 3<4<2 is actually equivalent to 1<2, which is of course very true:
>> 1<2
ans =
1
Dung Le on 5 Jan 2016
Thank you so much :) I got it!