Would anyone please help me with this Boolean related error?

Anyone knows why I keep getting an error for the below simple function:

A = [15, 16, -30];
B = [12, 35, 38];
Ind = A .> -20 && B .>= 15

Here is the error:

TypeError: non-boolean (BitVector) used in boolean context

Stacktrace:
 [1] top-level scope
   @ In[12]:3
 [2] eval
   @ ./boot.jl:360 [inlined]
 [3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base ./loading.jl:1116

You didn’t broadcast the &&. Importantly, you can’t broadcast the && until 1.7 (which is in beta stage). It’s trying to do a boolean comparison with the vector result of A .> -20. But it can only compare booleans.

You want

map(A, B) do a, b
    (a > -20) && (b >= 15)
end 
2 Likes

Many thanks! As a Matlab user, I find that very inconvenient :slight_smile:

What does map do? I have to convert my A to a?

You can also do

Ind = A .> -20 .& B .>= 15

note, one & instead of two &&.

This could lead to some errors, though, since it won’t error on numbers. Its a bit-wise operation.

julia> 5 & 6
4

map applies a function to each element of an iterator, collecting the result into a Vector. It’s a fundamental idiom in Julia, see ? map for more details.

1 Like

You may also do:

A = [15, 30, 45];
B = [20, 25, 30];
[a > 16 && b >= 30 for (a, b) in zip(A,B)]

which results in [0, 0, 1].

4 Likes

Unfortunately this is really dangerous, because the operator precedence of & is different from the precedence of &&:

julia> A = [15, 16, -30];

julia> B = [12, 35, 38];

julia> A .> -20 .& B .>= 15
3-element BitVector:
 0
 0
 0

julia> (A .> -20) .& (B .>= 15)
3-element BitVector:
 0
 1
 0

So you need parentheses to get the right behavior.

1 Like

On a sufficiently new Julia, meaning 1.7 I think, you can broadcast && too:

julia> A .> -20 .&& B .>= 15
3-element BitVector:
 0
 1
 0
1 Like