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 regularArray
in most operations.You can easily convert your integer matrix to a
BitArray
. Afterwards, applying a logical not works as expected.The crucial part here is that the element type (
eltype
) of aBitArray
isBool
, for which negation is obviously well defined. In this sense, you could also useB = Bool.(A)
to convert all the elements to booleans.