If you have an array a
of ints in MATLAB you can do logical(a)
to get a Boolean array where every nonzero entry is 1 and every 0 entry is 0. How do you do this in Julia?
Another option is to use the iszero
function, which gives you a clearer syntax:
julia> a = rand(0:3,2,2)
2×2 Array{Int64,2}:
0 3
0 1
julia> b = iszero.(a)
2×2 BitArray{2}:
1 0
1 0
You can find information about iszero
in here or by typing ?iszero
at the REPL.
The use of broadcasting is needed because that makes the function compare every element to zero. If you don't use it, it will return only true if all the matrix is zero or false if one element is different than zero.
You can construct this behavior by broadcasting the inequality operator.
julia> x
5×5 Array{Int64,2}:
0 -4107730642120626124 6654664427866713002 7518855061140735034 8818106399735122346
8091546149111269981 4315717857697687985 0 -5798218902015720994 1300970799075893685
-7301322994135835673 -2297242472677021645 -4021288767260950802 7892625078388936975 -1629449791447953082
1060255079487701867 -5212584518144622345 7329251290490888722 1375278257655605061 -4361465961064184585
-469090114465458856 6912712453842322323 -1577327221996471827 -5606008086331742040 1641289265656709209
julia> !=(0).(x)
5×5 BitArray{2}:
0 1 1 1 1
1 1 0 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
The result is a BitArray
, the canonical representation of a matrix with boolean values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With