Boolean operations on arrays?

1,527 views
Skip to first unread message

Daniel Carrera

unread,
Sep 21, 2015, 8:35:34 AM9/21/15
to julia...@googlegroups.com
Hello,

I have two boolean arrays and I am trying to obtain the boolean array resulting from a component-wise `AND`:

julia> [true, true, false] .&& [false, true, true]
ERROR: syntax: invalid identifier name "&&"

julia> [true, true, false] .& [false, true, true]
ERROR: type Array has no field &


Can anyone figure out what I'm doing wrong? I was hoping that `.&` and `.&&` would apply the operation on a per-component basis. Help?

Cheers,
Daniel.

Yichao Yu

unread,
Sep 21, 2015, 8:39:13 AM9/21/15
to Julia Users
julia> [true, true, false] & [false, true, true]
3-element Array{Bool,1}:
false
true
false



>
> Cheers,
> Daniel.

Daniel Carrera

unread,
Sep 21, 2015, 8:41:29 AM9/21/15
to julia...@googlegroups.com
It looks like I can get the right effect using component-wise multiplication:

julia> ![true, true, false] .* [false, true, true]
3-element Array{Bool,1}:
 false
 false
  true


Is this the correct solution or is this an ugly hack?

Cheers,
Daniel.


Matt Bauman

unread,
Sep 21, 2015, 9:28:46 AM9/21/15
to julia-users
The bitwise operations (&, |) broadcast over arrays and work just fine for this.  Watch out for their precedence, though: you need to wrap them in parentheses if you want to combine them with the result of comparisons `(A == 1) | (A == 2)`.

Seth

unread,
Sep 21, 2015, 11:24:40 AM9/21/15
to julia-users
Note that the broadcasting works for sparse matrices only on recent builds.

Daniel Carrera

unread,
Sep 21, 2015, 12:50:48 PM9/21/15
to julia-users

On Monday, 21 September 2015 14:39:13 UTC+2, Yichao Yu wrote:

julia> [true, true, false] & [false, true, true]
3-element Array{Bool,1}:
false
 true
false 

Thanks! What is the difference between & and && ? 

Sisyphuss

unread,
Sep 21, 2015, 1:09:31 PM9/21/15
to julia-users
& works for array
&& works for scale

Matt Bauman

unread,
Sep 21, 2015, 1:21:27 PM9/21/15
to julia-users
More concretely, && and || are control flow operators.  They short circuit.  Therefore, they require Boolean arguments and aren't real functions.  They're syntax.

& and | are bitwise operations and real, extendable functions.  They can operate on booleans *and* integers, performing bitwise arithmetic (often used for bit flags):

julia> 0x2345 & 0x0F0F
0x0305

julia> ans | 0x6070
0x6375

Daniel Carrera

unread,
Sep 21, 2015, 1:27:13 PM9/21/15
to julia...@googlegroups.com
Oh.... Thanks!
Reply all
Reply to author
Forward
0 new messages