What's the most efficient way to convert a Matrix{T} of size 1*N or N*1 in Julia to a Vector{T}?
14,966
Solution 1
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()
Solution 2
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
.
Solution 3
vec() is faster
const a = reshape([1:1000],1000,1);
@time vec(a);
elapsed time: 6.914e-6 seconds (184 bytes allocated)
@time squeeze(a,2);
elapsed time: 1.0336e-5 seconds (248 bytes allocated)
Related videos on Youtube
Author by
Ben Hamner
Updated on March 17, 2020Comments
-
Ben Hamner about 4 years
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
andb
are of typeArray{Int,2}
(i.e.Matrix{Int}
). What are the most efficient ways to converta
andb
to typeArray{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]
-
StefanKarpinski over 11 yearsOne important thing to note about both
vec
andreshape
is that they share memory with the underlying array for performance – that's whyvec
is so much faster than a comprehension, which creates a new array object, copying content. Thus, if you changea[1]
,v_aII[1]
will also change and vice versa, whereasv_a[1]
will be unaffected. -
Diego Javier Zea over 11 yearsGood, I didn't know about this function.
-
Diego Javier Zea over 11 yearsSeeing in the definitions, looks like squeeze has to be a little more slow than the other. github.com/JuliaLang/julia/blob/master/base/… I do a little benchmark, and I found: squeeze(m) : ( 2.97 +- 2 ) e-6 seconds vec(m) : ( 2.02 +- 2 ) e-6 seconds reshape(m,length(m)) : ( 1.72 +- 2 ) e-6 seconds Difference is very very small, but how one can expect by definitions, reshape(m,length(m)) is the faster option.