Assignment to size zero array, [in-place assign bug]?

Hi, just came across this. Should assigning to a zero size array not perhaps produce an error:

julia> a = zeros(0,1)
julia> a[:,1] .= [1]
0-element view(::Array{Float64,2}, :, 1) with eltype Float64

Regular behavior does work:

julia> zeros(1,1)[:,1] .= [1]
1-element view(::Array{Float64,2}, :, 1) with eltype Float64:
 1.0

On Julia 1.3.1. Hope Internals & Design is the right venue for this.

zeros(0,1) vs zeros(1,1) ?

I feel the the first assignment example should give an error, since it is not actually able to do the assignment (there is no memory to store the setting value). zeros(0,1) is completely flat, and assigning an array from a different size should not be allowed?

This example does work

a = zeros(2,3)
b = zeros(1,3)
b[1,:] = [1;2;3]
julia> a .= b
2×3 Array{Float64,2}:
 1.0  2.0  3.0
 1.0  2.0  3.0

So perhaps it is the intended behavior with repetition. If so then this is not a bug, but seems a bit odd.

It is able to assign to all elements. It’s just that there are none.

Cf

julia> all(isodd, zeros(0,1))
true
1 Like

It’s not repetition, it’s broadcasting, and your original example is broadcasting down to zero elements. But even if the target is empty, the dimensions must still satisfy the rules for broadcasting.

julia> a = zeros(0, 2)
0×2 Array{Float64,2}

julia> a .= ones(1, 1)
0×2 Array{Float64,2}

julia> a .= ones(1, 2)
0×2 Array{Float64,2}

julia> a .= ones(1, 3)
ERROR: DimensionMismatch("array could not be broadcast to match destination")
Stacktrace:
 [1] check_broadcast_shape at ./broadcast.jl:509 [inlined]
 [2] check_broadcast_shape at ./broadcast.jl:510 [inlined]
 [3] check_broadcast_axes at ./broadcast.jl:512 [inlined]
 [4] instantiate at ./broadcast.jl:259 [inlined]
 [5] materialize!(::Array{Float64,2}, ::Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{2},Nothing,typeof(identity),Tuple{Array{Float64,2}}}) at ./broadcast.jl:823
 [6] top-level scope at none:1

Addendum:
If you don’t want the broadcasting behavior, use regular assignment instead of dot assignment.

julia> a = zeros(0,1)
0×1 Array{Float64,2}

julia> a[:,1] = [1]
ERROR: DimensionMismatch("tried to assign 1-element array to 0×1 destination")
Stacktrace:
[...]

Broadcasting to zero

Thanks, that’s a good description.