Borrar filtros
Borrar filtros

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

13 visualizaciones (últimos 30 días)
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:
clear all clc A=xlsread('criteria.xlsx'); B=xlsread('panel.xlsx');
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);
x = mean(B(mask,3));
B(mask,5) = x;
y = std(B(mask,3));
B(mask,6) = y;
end
end
end
end
xlswrite('panel.xlsx',B)
Code 2:
clear all clc A=xlsread('criteria.xlsx'); B=xlsread('panel.xlsx');
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);
x = mean(B(mask,3));
B(mask,7) = x;
y = std(B(mask,3));
B(mask,8) = y;
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!

Respuesta aceptada

Stephen23
Stephen23 el 5 de En. de 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

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by