Construct a 2-d column array

Is there a quick way to create an 3x1 Array{ T , 2} where T is a type ?

[A, B, C, ...] or [A; B; C; ...] construct a 1-d array (vector).

[A B C ...] constructs a 2-d row array.

What about a 2-d column array? Does anyone know why [A; B; C; ...] wasn’t chosen for this task?

See this discussion for multiple suggestions (depending on whether you want to construct from existing contents, etc):

2 Likes

I guess reshape is the way to go, but intuitively I think [A; B; C] makes a lot of sense and would also remove the issue of two different syntaxes doing the same thing.

[A, B] and [A; B] don’t do the same thing, though:

julia> A = [1, 2, 3]; B = [4, 5];

julia> [A, B]
2-element Array{Array{Int64,1},1}:
 [1, 2, 3]
 [4, 5]   

julia> [A; B]
5-element Array{Int64,1}:
 1
 2
 3
 4
 5
2 Likes

Didn’t think about that, thanks.

I think that the cheapest solution, with the same cost as creating a vector, is hvcat:

julia> using BenchmarkTools

julia> @btime [1,2,3]
  34.418 ns (1 allocation: 112 bytes)
3-element Array{Int64,1}:
 1
 2
 3

julia> @btime reshape([1,2,3],:,1)
  101.557 ns (3 allocations: 208 bytes)
3×1 Array{Int64,2}:
 1
 2
 3

julia> @btime hvcat(1, 1,2,3)
  46.672 ns (1 allocation: 112 bytes)
3×1 Array{Int64,2}:
 1
 2
 3

It may be a bit annoying having to put that 1 as first argument, but easy to work around it, wrapping it in another function, e.g.

columnmatrix(args...) = hvcat(1, args...)
3 Likes

Julia 1.7 allows

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