The best way to convert Vector into Matrix in Julia?

22,688

Solution 1

Reshape should be the most efficient. From the docs:

reshape(A, dims): Create an array with the same data as the given array, but with different dimensions. An implementation for a particular type of array may choose whether the data is copied or shared.

julia> v = rand(3)
3-element Array{Float64,1}:
 0.690673 
 0.392635 
 0.0519467

julia> reshape(v, length(v), 1)
3x1 Array{Float64,2}:
 0.690673 
 0.392635 
 0.0519467

Solution 2

v[:,:] is probably the clearest way to do this.

For example:

julia> v=[1,2,3]
3-element Array{Int64,1}:
1
2
3

julia> m=v[:,:]
3x1 Array{Int64,2}:
1
2
3

julia> ndims(m)
2

Solution 3

Or just use:

v = [1, 2, 3]
hcat(v)

Result:

3×1 Array{Int64,2}:
 1
 2
 3
Share:
22,688
aberdysh
Author by

aberdysh

Updated on October 19, 2020

Comments

  • aberdysh
    aberdysh over 3 years

    Suppose I have a variable v of a type Vector.

    What would be the best / fastest way to just convert it into Matrix representation (for whatever reason)?

    To clarify, v'' will do the job, but is it the best way to do this?

    • amrods
      amrods over 8 years
      try using reshape.
    • Colin T Bowers
      Colin T Bowers over 6 years
      Just noting that in v0.6, v'' will no longer work, as this now converts v into a row vector, then back into a vector. reshape (as described below) is probably the best solution.
  • Jollywatt
    Jollywatt about 5 years
    We can now use reshape(v, :, 1), instead of finding length(v) explicitly. docs.julialang.org/en/v1/base/arrays/#Base.reshape
  • aberdysh
    aberdysh about 4 years
    This will allocate, so better to use reshape