Reputation: 673
I have two nxm matrices of 1's and 0's (call them A and B). I want to convert them to Boolean variables and then apply "and" and "or" operations to them. In python, this is easy:
A = np.array(A, dtype=bool)
B = np.array(B, dtype=bool)
A | B
A & B
However, I want to do the same thing in Julia, and I am having some issues. I first convert to Boolean via
A = convert(Array{Bool}, A)
B = convert(Array{Bool},B)
But then I do A&&B, I get
TypeError: non-boolean (Array{Bool,2}) used in boolean context
What am I doing wrong?
Upvotes: 2
Views: 1293
Reputation: 69839
We first create matrices that store 0
-1
values:
julia> using Random
julia> Random.seed!(1234);
julia> A = rand([0, 1], 3, 4)
3×4 Array{Int64,2}:
0 0 1 1
0 1 1 0
1 0 1 0
julia> B = rand([0, 1], 3, 4)
3×4 Array{Int64,2}:
1 1 1 0
0 1 1 1
0 1 1 1
Then broadcast using .
the Bool
constructor to get boolean matrices:
julia> A_bool = Bool.(A)
3×4 BitArray{2}:
0 0 1 1
0 1 1 0
1 0 1 0
julia> B_bool = Bool.(B)
3×4 BitArray{2}:
1 1 1 0
0 1 1 1
0 1 1 1
Similarly use the .
broadcasting on &
and |
operators to get what you want:
julia> A_bool .| B_bool
3×4 BitArray{2}:
1 1 1 1
0 1 1 1
1 1 1 1
julia> A_bool .& B_bool
3×4 BitArray{2}:
0 0 1 0
0 1 1 0
0 0 1 0
Note that in this particular case using |
and &
on the original matrices would get an equivalent result (but the matrices would contain 0
-1
integers):
julia> A .| B
3×4 Array{Int64,2}:
1 1 1 1
0 1 1 1
1 1 1 1
julia> A .& B
3×4 Array{Int64,2}:
0 0 1 0
0 1 1 0
0 0 1 0
Upvotes: 6