What's the most efficient way to convert a Matrix{T} of size 1*N or N*1 in Julia to a Vector{T}?
For example, say I have
a = [1,3,5] b = a'
Both a
and b
are of type Array{Int,2}
(i.e. Matrix{Int}
). What are the most efficient ways to convert a
and b
to type Array{Int,1}
(i.e. Vector{Int}
)?
One approach is:
a_vec = [x::Int for x in a] b_vec = [x::Int for x in b]
Conversion of a Matrix into a Row Vector. This conversion can be done using reshape() function along with the Transpose operation. This reshape() function is used to reshape the specified matrix using the given size vector.
Creating a Vector 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,..])
Julia provides a very simple notation to create matrices. A matrix can be created using the following notation: A = [1 2 3; 4 5 6]. Spaces separate entries in a row and semicolons separate rows. We can also get the size of a matrix using size(A).
You can use the vec()
function. It's faster than the list comprehension and scales better with number of elements ;) For a matrix of 1000x1:
julia> const a = reshape([1:1000],1000,1); julia> typeof(a) Array{Int64,2} julia> vec_a = [x::Int for x in a]; julia> typeof(vec_a) Array{Int64,1} julia> vec_aII = vec(a); julia> typeof(vec_aII) Array{Int64,1}
6.41e-6 seconds # list comprehension
2.92e-7 seconds # vec()
I would tend to use squeeze
to do this if the matrix is 1xN
or Nx1
:
squeeze(ones(3, 1)) squeeze(ones(1, 3))
Not sure if that's more efficient than using vec
or reshape
.
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