Can't concatenate a matrix to `Any[]` horizontally

Block1:

a = []
b = [1 2; 3 4]
a = vcat(a, b) # or a = [a; b]

Block2:

a = []
b = [1 2; 3 4]
a = hcat(a, b) # or a = [a b]

Question: Block1 works but Block2 doesn’t. Why?

Block 1 doesn’t work for me

julia> a = []
Any[]

julia> b = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> a = vcat(a, b) # or a = [a; b]
ERROR: DimensionMismatch: number of columns of each array must match (got (1, 2))
Stacktrace:
 [1] _typed_vcat(::Type{Any}, A::Tuple{Vector{Any}, Matrix{Int64}})
   @ Base ./abstractarray.jl:1702

Are you sure?

julia> a = []
Any[]

julia> b = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> a = vcat(a, b) 
ERROR: DimensionMismatch: number of columns of each array must match (got (1, 2))

:astonished:

julia> a = []
Any[]

julia> b = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> a = vcat(a, b)
2×2 Matrix{Any}:
 1  2
 3  4

If I run Block2 it reports:

ERROR: DimensionMismatch: mismatch in dimension 1 (expected 0 got 2)

Julia Version 1.9.0

I would say this, as a first thought, that being a vector and not a matrix it can also be vertically concatenated with a matrix (which is reinterpreted as a vector?) that has different dimensions.
While to concatenate horizontally the dimensions must match.
IF instead of the vector you define an empty matrix the problem also occurs for vcat

julia> a = [;;]
0×0 Matrix{Any}

julia> b = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> a = vcat(b, a) # or a = [a; b]
ERROR: DimensionMismatch: mismatch in dimension 2 (expected 2 got 0)  
1 Like

Thanks. Your explanation makes sense to me.

But now how to explain the other more confusing problem: why can’t they run Block1?

Yes looks like this behaviour changed between 1.9 and 1.10.

1 Like

I tried defining a=Int[] and this seems to change the behavior between
vcat(a,b) and cat(a,b,dims=Val(1)) which should be equivalent

I tried to see what’s behind cat(a,b,dims=Val(1)), but it’s too complicated to follow