Reputation: 327
The problem is difficult to describe (hence the bad titel), it is easier to show it:
matr =
[
1 1 3
2 1 10
3 2 3
13 8 10]
i=1
print(matr[:,2].==i .* matr[:,3].!=i)
x = matr[:,2].==i
y = matr[:,3].!=i
print(x .* y)
The first and the second print() should be equivalent. Regardless, the first one prints Bool[false, false, false, false]
the second one prints Bool[true, true, false, false]
.
Since the first result is wrong, I am wondering how this problem arises and how it can be prevented.
Upvotes: 0
Views: 71
Reputation: 5583
This is an operator precedence issue. What you write in the first print
is not what you intended.
print(matr[:,2].==i .* matr[:,3].!=i)
This is equivalent to (see the parentheses)
print(matr[:,2] .== (i .* matr[:,3]) .!=i)
which is a chaining comparison, so that both matr[k,2] == (i .* matr[k,3]))
and matr[k,2] == (i .* matr[k,3]))
must be true for the k
th index in order for the chaining comparison to return true
for the k
th index.
Instead you can write the same term with explicit parentheses to take care of the precedence issue.
print((matr[:,2].==i) .* (matr[:,3].!=i))
Instead of multiplication, you can broadcast &
.
print((matr[:,2].==i) .& (matr[:,3].!=i))
Both of these should give you the right answer.
Upvotes: 2