How to create a 2x1 Array?

It was discussed in the lead up to 1.0 whether [1; 2; 3] should construct a vector or a matrix. But note that there’s nothing special about two dimensions in concatenation syntax in general:

julia> [rand(2); rand(2)]
4-element Array{Float64,1}:
 0.528860561644692
 0.2992626181507161
 0.6659761151342882
 0.423705081212141

julia> [rand(2, 2, 2); rand(2, 2, 2)]
4×2×2 Array{Float64,3}:
[:, :, 1] =
 0.91018   0.0499205
 0.136608  0.128014
 0.621301  0.0150574
 0.58328   0.694085

[:, :, 2] =
 0.533126  0.0534934
 0.974593  0.808837
 0.851397  0.407801
 0.699824  0.928702

julia> [rand(2, 2, 2) rand(2, 2, 2)]
2×4×2 Array{Float64,3}:
[:, :, 1] =
 0.590656    0.106946  0.7484     0.369444
 0.00954534  0.925276  0.0796861  0.467557

[:, :, 2] =
 0.482709  0.0137462  0.241554  0.566803
 0.970356  0.640528   0.737484  0.684

The [... ; ...] syntax calls vcat which does “concatenation along the first dimension”—regardless of how many dimensions the inputs have. If they’re vectors, it produces a vector, if they’re matrices, it produces a matrix, if they’re 3-tensors, it produces a 3-tensor, and so on. There does, however, have to be at least one output dimension since you’re concatenating at least two things vertically, so vcat of scalars does produce a vector. If we’d made [1; 2; 3] produce a 3×1 matrix then that would be arbitrarily treating 2-dimensionally arrays specially, which is a thing that Julia tries very hard to avoid and it would have to lower to something other than just plain vcat (or we’d have to make vcat treat matrices specially as well).

5 Likes