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
Author by
aberdysh
Updated on October 19, 2020Comments
-
aberdysh over 3 years
Suppose I have a variable
v
of a typeVector
.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 over 8 yearstry using
reshape
. -
Colin T Bowers over 6 yearsJust noting that in v0.6,
v''
will no longer work, as this now convertsv
into a row vector, then back into a vector.reshape
(as described below) is probably the best solution.
-
-
Jollywatt about 5 yearsWe can now use
reshape(v, :, 1)
, instead of findinglength(v)
explicitly. docs.julialang.org/en/v1/base/arrays/#Base.reshape -
aberdysh about 4 yearsThis will allocate, so better to use reshape