Jim Maas
Jim Maas

Reputation: 1729

Julia, integer vs boolean results from selection of instances in two arrays

I've got my 3d array called Pop. I want find out how many times two different conditions are met, and they both work for me independently but I can't put the two together.

Pop[end, :, 1] .== 3

works ok, produces an integer vector of 1's and 0's which is correct. Also

Pop[end-1, :, 1] .== 4

works, again returns integer vector, however when I put the two together as:

count(Pop[end, :, 1] .== 3 && Pop[end-1, :, 1] .== 4)

I get this error:

ERROR: TypeError: non-boolean (BitArray{1}) used in boolean context

Which sort of helps, can see that the two numeric arrays can not be compared in a boolean way. What is wrong with my syntax to get the count of the number of times both of the conditions are met. Simple I know but I can't get it! Thx. J

Upvotes: 2

Views: 326

Answers (1)

MarcMush
MarcMush

Reputation: 1488

&& is a short-circuiting boolean, which means that if the first term is true, the rest isn't evaluated (see documentation). It also means it's only for a singular booleans and it cannot be broadcasted over an array.

& is the bitwise AND operator (documentation), that you want to use here, because it can be broadcasted over arrays with the syntax .&, the same way you use .==

julia> [true, true, false, false] .& [true, false, true, false]
4-element BitVector:
 1
 0
 0
 0

Update

in Julia 1.7+, the short-circuiting operators && and || can now be dotted to participate in broadcast fusion as .&& and .|| (#39594):

julia> [true, true, false, false] .&& [true, false, true, false]
4-element BitVector:
 1
 0
 0
 0

Upvotes: 4

Related Questions