I need to apply "not" operator to matrix of zeros and ones in Julia. In Matlab I would do this:
A=not(B);
In Julia I tried doing this:
A = .~ B;
and
A = .! B;
It should turn zeros to ones and ones to zeros but I get error as a result or all matrix elements are some negative numbers that I didn't enter. Thanks in advance!
The issue with A = .!B
is that logical negation, !(::Int64)
, isn't defined for integers. This makes sense: What should, say, !3
reasonably give?
Since you want to perform a logical operation, is there a deeper reason why you are working with integers to begin with?
You could perhaps work with a BitArray
instead which is vastly more efficient and should behave like a regular Array
in most operations.
You can easily convert your integer matrix to a BitArray
. Afterwards, applying a logical not works as expected.
julia> A = rand(0:1, 5,5)
5×5 Array{Int64,2}:
0 0 0 1 1
0 1 0 0 1
0 1 1 1 0
1 1 0 0 0
1 1 1 0 0
julia> B = BitArray(A)
5×5 BitArray{2}:
0 0 0 1 1
0 1 0 0 1
0 1 1 1 0
1 1 0 0 0
1 1 1 0 0
julia> .!B
5×5 BitArray{2}:
1 1 1 0 0
1 0 1 1 0
1 0 0 0 1
0 0 1 1 1
0 0 0 1 1
The crucial part here is that the element type (eltype
) of a BitArray
is Bool
, for which negation is obviously well defined. In this sense, you could also use B = Bool.(A)
to convert all the elements to booleans.