Julia: calculate an inner product using boolean algebra
Asked Answered
P

1

7

I've got two boolean vectors a = [1,1,1] and b = [0,1,1] where obviously 1 stands for true and 0 for false.

I want to calculate their inner product using Boolean algebra. The result I want is therefore

1*0 + 1*1 + 1*1 = 0 + 1 + 1 = 0

because addition plays the role of exclusive or (XOR).

I know that the product part can be done like this

a = [true, true, true] # could also use ones(Bool, 3)
b = [false, true, true]

bitwise_prod = a .& b

but I don't know how to do the sum. Any ideas?

Pastypat answered 18/5, 2018 at 9:32 Comment(0)
P
5

I've actually found a good way now. First of all I don't need to use Boolean variables

a = [1, 1, 1]  # or ones(Int, 3)
b = [0, 1, 1]

I can then use reduce with the xor function.

reduce(xor, a .& b)

Note that I tried using the bitwise xor operator $ that is found in the documentation (inside an anonymous function) but this operator is deprecated and Julia 0.6.2 suggests the xor function instead. I do think having the function name makes it very neat.

Pastypat answered 18/5, 2018 at 9:48 Comment(3)
, which you get by typing \xor, should work, too.Wolfe
You will need to use dot-broadcasted a .& b in 0.7 or later. You can also avoid allocating an intermediate array by mapreduce(x->x[1]&x[2], xor, zip(a,b))Plebeian
The mapreduce version is a lot less readable though, compared to reduce(xor, a .& b). Unless your arrays are really big, the reduce version is probably preferrable.Cronk

© 2022 - 2024 — McMap. All rights reserved.