Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most efficient way to convert a Matrix{T} of size 1*N or N*1 in Julia to a Vector{T}?

Tags:

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] 
like image 657
Ben Hamner Avatar asked Jan 20 '13 03:01

Ben Hamner


People also ask

Can we convert matrix to vector?

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.

How do you make a vector in Julia?

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,..])

How do you create a matrix in Julia?

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).


2 Answers

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()

like image 151
Diego Javier Zea Avatar answered Sep 19 '22 16:09

Diego Javier Zea


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.

like image 37
John Myles White Avatar answered Sep 18 '22 16:09

John Myles White