Suppose we have a 6-element array in Julia, for example, Int64[1,1,2,3,3,4]
. If we want to compare two arrays elementwise, we know we can use ".=="; but my goal is to do all the pairwise comparisons inside the above array: if the elements (i,j) of each pair are equal, I set it to 1 (or true), but if they are different, I set it to 0. All the pairwise comparisons are stored in a 6x6 matrix. Is it possible to do that in Julia without the loop for? Thank you.
Asked
Active
Viewed 789 times
0

coolsv
- 781
- 5
- 16
1 Answers
12
You can use the fact that broadcasting will compare rows to columns to simply do a comparison between the array and its transpose:
julia> A = [1,1,2,3,3,4]
6-element Array{Int64,1}:
1
1
2
3
3
4
julia> A .== A'
6×6 BitArray{2}:
true true false false false false
true true false false false false
false false true false false false
false false false true true false
false false false true true false
false false false false false true

Chris Rackauckas
- 18,645
- 3
- 50
- 81
-
1Wow, wonderful!!! I tried A.== A without the quote at the end with no success! The solution was so simple! Thank you! – coolsv May 14 '18 at 19:34
-
3On version 0.6 I surprisingly find that `[a==b for a in A, b in B]` is about 4 times faster. – DNF May 14 '18 at 20:55
-
2`[a == b for a in A', b in A]` is about 3 times faster in Julia v0.7 too, though the result is a `1x6x6 Array{Bool, 3}`. Adding a `squeeze` call to get a `6x6 Array{Bool, 2}` brings the time back up to the `.==`'s time. – Sundar R May 21 '18 at 08:13