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.
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.
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,..])
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With