Julia - combining vectors into the matrix
Two ways I know of:
julia> x = [1,2];
julia> y = [3,4];
julia> vcat(x', y')
2×2 Array{Int64,2}:
1 2
3 4
julia> permutedims(hcat(x, y))
2×2 Array{Int64,2}:
1 2
3 4
Note that in vcat(x', y')
the operation x'
is adjoint so it should not be used if you are working with complex numbers or vector elements that do not have adjoint defined (e.g. strings). Therefore then permutedims
should be used but it will be slower as it allocates. A third way to do it is (admittedly it is more cumbersome to type):
julia> [reshape(x, 1, :); reshape(y, 1, :)]
2×2 Array{Int64,2}:
1 2
3 4
It is non allocating like [x'; y']
but does not do a recursive adjoint.
EDIT:
Note for Cameron:
julia> x = repeat(string.('a':'z'), 10^6);
julia> @btime $x';
1.199 ns (0 allocations: 0 bytes)
julia> @btime reshape($x, 1, :);
36.455 ns (2 allocations: 96 bytes)
so reshape
allocates but only minimally (it needs to create an array object, while x'
creates an immutable struct which does not require allocation).
Also I think it was a design decision to allocate. As for isbitsunion
types actually reshape
returns a struct so it does not allocate (similarly like for ranges):
julia> @btime reshape($x, 1, :)
12.211 ns (0 allocations: 0 bytes)
1×2 reshape(::Array{Union{Missing, Int64},1}, 1, 2) with eltype Union{Missing, Int64}:
1 missing