Daniel Kaszyński
Daniel Kaszyński

Reputation: 309

Julia - combining vectors into the matrix

Let's assume I have two vectors x = [1, 2] and y = [3, 4]. How to best combine them to get a matrix m = [1 2; 3 4] in Julia Programming language? Thanks in advance for your support.

Upvotes: 17

Views: 4814

Answers (4)

Benoit Pasquier
Benoit Pasquier

Reputation: 2995

What about

vcat(transpose(x), transpose(y))

or

[transpose(x); transpose(y)]

Upvotes: 7

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42194

One more option - this one works both with numbers and other objects as Strings:

julia> rotl90([y x])
2×2 Array{Int64,2}:
 1  2
 3  4

Upvotes: 7

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69819

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

Upvotes: 12

Scott Staniewicz
Scott Staniewicz

Reputation: 742

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

Upvotes: 8

Related Questions