Matching array elements in Julia

With x = Any[[1,2],[2,3],[3,4],[4,5]] , I tried the following line with Julia0.4.0

 x[ x .== [3,4] ] 

but this led to an error

 ERROR: DimensionMismatch("arrays could not be broadcast to a common size") 

I expected it to give something like Any[ [3,4] ] , because

 x[3] == [3,4] # => true 

no problem. Although this operation alone cannot be useful, I would like to know what the error message means. Therefore, I would appreciate any hints why this error occurs.

+6
source share
2 answers

To make a phased comparison, Julia requires that both arrays have the same number of elements. This can be achieved in this case with the understanding:

 julia> x = Any[[1,2],[2,3],[3,4],[4,5]] 4-element Array{Any,1}: [1,2] [2,3] [3,4] [4,5] julia> x[x.==[[3,4] for i in 1:length(x)]] 1-element Array{Any,1}: [3,4] 

So, the question in my mind was β€œwhy didn't Julia pass [3,4] into this form automatically?” The following example translates correctly:

 julia> y = [1,2,3,4] 4-element Array{Int64,1}: 1 2 3 4 julia> y.==3 4-element BitArray{1}: false false true false julia> y[y.==3] 1-element Array{Int64,1}: 3 

It seems that Julia’s broadcasting mechanism cannot conclude that we want [3,4] broadcast in [[3,4],[3,4],[3,4],[3,4]] , not any other kind of array.

+5
source

You can help Julia figure out a bit how to translate the second variable by writing a comparison as follows:

 julia> x .== Any[[3, 4]] 

You get bitarray, as expected:

 4-element BitArray{1}: false false true false 

Thus, indexing with a comparison result also works:

 julia> x[ x .== Any[[3,4]] ] 1-element Array{Any,1}: [3,4] 
+3
source

Source: https://habr.com/ru/post/988681/


All Articles