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 it resulted in 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
is no problem. Although this operation itself may not be useful, I would like to know what the error message means. So I would appreciate any hints why this error occurs.
To make an element-by-element comparison, Julia requires that both arrays have the same number of elements. This can be achieved in this case with a comprehension:
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 doesn't Julia broadcast the [3,4]
into this shape automatically?". The following example is broadcast 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 appears that Julia's broadcast mechanism is unable to infer that we want [3,4]
to be broadcast into [[3,4],[3,4],[3,4],[3,4]]
rather than some other shape of array.
You can help Julia a little in figuring out how to broadcast the second variable by writing the comparison like this:
julia> x .== Any[[3, 4]]
You get a BitArray out as expected:
4-element BitArray{1}:
false
false
true
false
So indexing with the result of the comparison works too:
julia> x[ x .== Any[[3,4]] ]
1-element Array{Any,1}:
[3,4]
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