Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia - combining vectors into the matrix

Tags:

julia

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.

like image 701
Daniel Kaszyński Avatar asked Nov 13 '20 22:11

Daniel Kaszyński


People also ask

How do I add to an array in Julia?

Julia allows adding new elements in an array with the use of push! command. Elements in an array can also be added at a specific index by passing the range of index values in the splice! function.

How do you write a vector in Julia?

A Vector in Julia can be created with the use of a pre-defined keyword Vector() or by simply writing Vector elements within square brackets([]). There are different ways of creating Vector. vector_name = [value1, value2, value3,..] or vector_name = Vector{Datatype}([value1, value2, value3,..])

How do you find the dimensions of a matrix in Julia?

Get array dimensions and size of a dimension in Julia – size() Method. The size() is an inbuilt function in julia which is used to return a tuple containing the dimensions of the specified array. This returned tuple format is (a, b, c) where a is the rows, b is the columns and c is the height of the array.


1 Answers

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
like image 173
Bogumił Kamiński Avatar answered Sep 18 '22 04:09

Bogumił Kamiński