Why does [1; 2; 3] creates an Array of dimension 1 instead of 3x1 Array of dimnesion 2

Hello, following the docs , is a separator while space is a horizontal concatination and ; is vertical one. Now, to have a consistant behavior, why not do it the following:

julia> [1, 2, 3]
3-element Array{Int64,1}:
 1
 2
 3

julia> [1 2 3]
1×3 Array{Int64,2}:
 1  2  3

julia> [1; 2; 3]
3×1 Array{Int64,2}:
 1
 2
 3

instead of the current behavior:

julia> [1, 2, 3]
3-element Array{Int64,1}:
 1
 2
 3

julia> [1 2 3]
1×3 Array{Int64,2}:
 1  2  3

julia> [1; 2; 3]
3-element Array{Int64,1}:
 1
 2
 3

Because i case of [1 2; 3 4; 5 6] it will create a 3x2 Array anyway.

I’m not sure I know the definitive answer to your question, but the semi-colon has another utility when constructing arrays. For example, consider the following two arrays, x and y:

x = [1,[2,3]]
y = [1;[2,3]]

x is a two element array with its first element being 1 and its second element being [2,3]. On the other hand, y is a three element array [1,2,3].

For another example you could try:

z = [1:3;4:6]

vs

z = [1:3,4:6]

I agree that this is confusing, and it’s something I was confused by as well. The best explanation I have is that ; is actually the vertical concatenation operator. So [1; [2, 3]] is equivalent to vcat(1, [2, 3]) which is how we get [1, 2, 3]. By extension, [1; 2; 3] is also vcat(1, 2, 3) which is again [1, 2, 3] (that is, a Vector which is by convention a column vector). Vertical concatenation doesn’t create a new dimension if all of its inputs are 1- or 0-dimensional, so using ; doesn’t give you a 2-dimensional 3x1 matrix, even though you might expect it to.

1 Like

For reference the most succinct ways to produce an Nx1 matrix are

julia> [1 2 3]'
3×1 Array{Int64,2}:
 1
 2
 3

julia> v = [1, 2, 3]
3-element Array{Int64,1}:
 1
 2
 3

julia> hcat(v)
3×1 Array{Int64,2}:
 1
 2
 3

Just for reference:

this will not produce a matrix in Julia v0.7. Now that we take matrix transpose seriously, it produces an Adjoint:

julia> [1, 2, 3]'
1×3 LinearAlgebra.Adjoint{Int64,Array{Int64,1}}:
 1  2  3

this in turn actually simplifies a lot of internal stuff, as x' * y no longer has to have a special expansion rule to turn it into a call to the cryptically-named Ac_mul_b.

Edit: oops, linked to the wrong “taking foo seriously” issue

Thanks for the explanations. Now I kind of understand the reasons :wink:

Anyway the Adjoint type will have dimension 2 and size Nx1, as expected for a matrix. Effectively, it is a matrix that runs faster :sweat_smile:.