# How to convert Vector of Vectors to Matrix

**URL:** <https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609>\
**Category:** General Usage\
**Tags:** question, arrays\
**Created:** [December 5, 2021, 1:35pm UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609 "2021-12-05T13:35:53Z")\
**Posts on this page:** 20\
**Page:** 2

<div class="post-metadata">

**Author:** ![ga72kud](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ga72kud/32/32180_2.png) [@ga72kud](https://discourse.julialang.org/u/ga72kud)\
**Post date:** [March 25, 2022, 9:22am UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/21 "2022-03-25T09:22:45Z")

</div>

I think I come to an understanding of how the splatting command works. Thank you, it is very useful.

```julia
julia> hcat(x)
3×1 Matrix{Any}:
  [1.0, 3.0]
 2.0
 3.0

julia> hcat(x...)
ERROR: DimensionMismatch("mismatch in dimension 1 (expected 2 got 1)")
Stacktrace:
  [1] _cs
    @ ./abstractarray.jl:1626 [inlined]
  [2] _cshp
    @ ./abstractarray.jl:1622 [inlined]
  [3] _cat_size_shape(dims::Tuple{Bool, Bool}, shape::Tuple{Int64, Int64}, X::Float64, tail::Float64)
    @ Base ./abstractarray.jl:1602
  [4] cat_size_shape(::Tuple{Bool, Bool}, ::Vector{Float64}, ::Float64, ::Vararg{Float64, N} where N)
    @ Base ./abstractarray.jl:1600
  [5] _cat_t(::Val{2}, ::Type{Float64}, ::Vector{Float64}, ::Vararg{Any, N} where N)
    @ Base ./abstractarray.jl:1646
  [6] cat_t(::Type{Float64}, ::Vector{Float64}, ::Vararg{Any, N} where N; dims::Val{2})
    @ Base ./abstractarray.jl:1643
  [7] _cat
    @ ./abstractarray.jl:1641 [inlined]
  [8] #cat#129
    @ ./abstractarray.jl:1781 [inlined]
  [9] hcat(::Vector{Float64}, ::Float64, ::Float64)
    @ Base ./abstractarray.jl:1761
 [10] top-level scope
    @ none:1

julia> x=[[1., 3.], [2., 2.], [3., 3.]]
3-element Vector{Vector{Float64}}:
 [1.0, 3.0]
 [2.0, 2.0]
 [3.0, 3.0]

julia> hcat(x...)
2×3 Matrix{Float64}:
 1.0 2.0 3.0
 3.0 2.0 3.0

```

---

<div class="post-metadata">

**Author:** ![rocco\_sprmnt21](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rocco_sprmnt21/32/20127_2.png) [@rocco\_sprmnt21](https://discourse.julialang.org/u/rocco_sprmnt21)\
**Post date:** [March 25, 2022, 12:36pm UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/22 "2022-03-25T12:36:46Z")

</div>

```julia
vov = [rand(0:1,100) for _ in 1:100_000]
r=size(vov)[1]
c=size(vov[1])[1]
reshape(reduce(vcat,vov),(r,c)) 

```

---

<div class="post-metadata">

**Author:** ![overshiki](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/overshiki/32/43161_2.png) [@overshiki](https://discourse.julialang.org/u/overshiki)\
**Post date:** [October 2, 2022, 1:37pm UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/23 "2022-10-02T13:37:05Z")

</div>

Hi all,  
I came up with this one, where people can handle nested vectors of any level:

```julia
unsqueeze(a::Array) = begin 
    nsize = foldl(append!, size(a); init=[1])
    return reshape(a, Tuple(nsize))
end
stack(vs::Vector{T}) where T<:Vector = begin
    return reduce(vcat, map(unsqueeze, map(stack, vs)))
end
stack(vs::Vector{T}) where T<:Real = vs

```

some use cases:

```julia
julia> stack([[1,2,3], [1,2,3]])
2×3 Matrix{Int64}:
 1 2 3
 1 2 3

julia> stack([[[1],[2],[3]], [[1],[2],[3]]])
2×3×1 Array{Int64, 3}:
[:, :, 1] =
 1 2 3
 1 2 3

```

The idea is that just unsqueeze every array at the first dimension, then do `vcat`, and recursively repeat this over and over again, until the targeted array is returned.

cheers!

---

<div class="post-metadata">

**Author:** ![alanedelman](https://avatars.discourse-cdn.com/v4/letter/a/ecd19e/32.png) [@alanedelman](https://discourse.julialang.org/u/alanedelman)\
**Post date:** [November 19, 2022, 4:20pm UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/24 "2022-11-19T16:20:18Z")

</div>

I wish Matrix( vector\_of\_vectors ) would result in the matrix  
code would be so easy to read

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [November 19, 2022, 5:05pm UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/25 "2022-11-19T17:05:53Z")

</div>

[Welcome to the Julia community](https://news.mit.edu/2018/julia-language-co-creators-win-james-wilkinson-prize-numerical-software-1226) in your first post, @alanedelman.

---

<div class="post-metadata">

**Author:** ![ForceBru](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/forcebru/32/21389_2.png) [@ForceBru](https://discourse.julialang.org/u/ForceBru)\
**Post date:** [January 4, 2023, 2:11pm UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/26 "2023-01-04T14:11:07Z")

</div>

> [@alanedelman](#):
>
> I wish Matrix( vector\_of\_vectors ) would result in the matrix  
> code would be so easy to read

Right?! This would make so much sense! A vector of equal-size vectors is a matrix! Julia even displays vectors of vectors neatly _by rows_ (well, all vectors are displayed by rows, but this looks a lot like a matrix):

```julia
julia> sol.u
1001-element Vector{Vector{Float64}}:
 [1.0, 0.0, 0.0]
 [1.2714553023510824, 2.5502478518250142, 0.1141384466168722]
 [3.9131447607344776, 8.433083437324328, 1.2683805363770986]
 [11.696231301993413, 22.993582131160995, 11.769786900084997]
 [19.698658008680177, 16.751621637382875, 45.82588214497926]
 [6.503654894191205, -8.508354690536336, 38.091997347142616]
 [-3.332076962123722, -8.698838751487166, 28.734916780144353]
 [-6.535890901038596, -8.425700745706362, 25.905899192608068]
...

```

`Matrix(sol.u)` is easy to read _and_ easy to write: want to convert stuff to a matrix? - use the `Matrix` constructor!

But no, here we have 25 comments and a bunch of complex solutions:

- `mapreduce(permutedims, vcat, x)` is complex because, arguably, `mapreduce` is an advanced concept from functional programming, [big data and Apache Hadoop](https://en.wikipedia.org/wiki/MapReduce). This also requires knowing what `mapreduce`, `permutedims` and `vcat` do - all this for converting a vector of vectors into a matrix? IMO, it’s way too general.

- `permutedims(hcat(x...))` is complex because I need to know what `permutedims` and `hcat` do to use this. I also need to splat my potentially huge vector `x` and thus pass a million arguments to `hcat`. Indeed, [“don’t use splatting of large arrays”](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/12).

- `reduce(vcat,transpose.(x))` again requires me to know three unrelated functions. Okay, `transpose` is simple because it does what its name says. But it’s _not_ immediately clear that this incantation builds a matrix from a vector of vectors. Why write this convoluted code instead of `Matrix(vec_of_vecs)`??

- `reduce(hcat,x)'` is basically the same as the previous point.

- 

> [@guilhermebodin](#):
>
> I made this function in a package

IMO, this is the most straightforward code in this thread. However, shouldn’t this be part of the standard library?

- 

> [@aplavin](#):
>
> There are already packages with such a function: see `combinedims()` in `SplitApplyCombine.jl`

I find it disturbing that I _can_ install a package to cleanly convert a vector of vectors to a matrix. It could simply be one of `Matrix`’s constructors.

---

<div class="post-metadata">

**Author:** ![sijo](https://avatars.discourse-cdn.com/v4/letter/s/da6949/32.png) [@sijo](https://discourse.julialang.org/u/sijo)\
**Post date:** [January 4, 2023, 2:21pm UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/27 "2023-01-04T14:21:23Z")

</div>

Julia 1.9 (available in beta right now) has a new `stack` function:

```julia
a = [1,2,3]
b = [4,5,6]

julia> stack([a,b])
3×2 Matrix{Int64}:
 1 4
 2 5
 3 6

julia> stack([a,b], dims=1)
2×3 Matrix{Int64}:
 1 2 3
 4 5 6

```

---

<div class="post-metadata">

**Author:** ![mit.edelman](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mit.edelman/32/18467_2.png) [@mit.edelman](https://discourse.julialang.org/u/mit.edelman)\
**Post date:** [January 4, 2023, 2:23pm UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/28 "2023-01-04T14:23:18Z")

</div>

stack is nice but Matrix is better, can we have both?  
I wish almost every data structure could be "Matrix"ified to some default  
even if it’s not what every user would want

it’s just give me a Matrix da\*\* it function , i don’t want to look up a new command

---

<div class="post-metadata">

**Author:** ![ForceBru](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/forcebru/32/21389_2.png) [@ForceBru](https://discourse.julialang.org/u/ForceBru)\
**Post date:** [January 4, 2023, 2:30pm UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/29 "2023-01-04T14:30:56Z")

</div>

This is actually really useful and seems to be by far the most straightforward way of doing this. This function actually _tells me_ what it’s doing (`stack`ing stuff), so it’s easy to read and write. Very nice!

`Matrix(thing)` would’ve been even better, though. It just makes more sense and makes code even more readable. Of course, “makes more sense”, “most straightforward” and “more readable” aren’t terribly objective arguments, but come on, `Matrix(stuff)` _is_ easier to read, so why not have it?

---

<div class="post-metadata">

**Author:** ![sijo](https://avatars.discourse-cdn.com/v4/letter/s/da6949/32.png) [@sijo](https://discourse.julialang.org/u/sijo)\
**Post date:** [January 4, 2023, 3:34pm UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/30 "2023-01-04T15:34:47Z")

</div>

I think there’s a kind of convention in Julia to design APIs like this:

- Define a **constructor** such as `Matrix` for creating instances through a trivial operation (wrapping the arguments, initializing to a default value, etc.)
- Define a **function** (with name in lowercase) for more complex operations. The function does the heavy work and eventually calls a constructor to create the instance.

I remember reading about this somewhere but a quick look at the manual didn’t yield anything.

Anyway I think it’s a good principle for Julia: it’s a great language to write generic code, in which case you don’t actually know the type of the result. So you cannot directly call a constructor such as `Matrix` because you don’t know if the result should be a `Matrix` or another fancy array type such as `OffsetArray` or `ElasticArray` or whatever. The type of the result depends on the type of the argument (is it a list of `Vector`, or vectors of some fancy type that has defined it’s own version of `stack`?).

Also, there may be other sensible ways to make a matrix from a list of vectors. For example, you could define a function to make a matrix from 3 vectors: a vector of values, a vector of `i` indices and a vector of `j` indices. Then should the `Matrix` function concatenate the vectors, or use them as values and indices for the new matrix? You don’t have this problem if you define `stack` for concatenation and `matrix_from_vij` (or whatever) for the second option.

There are trade offs of course. The worst is probably that it’s harder this way to find the “right” function for the job. For example, ideally the documentation for `Matrix` would point to all the relevant functions for creating matrices, but currently it only mentions `fill`, `zeros`, `undef` and `similar`.

---

<div class="post-metadata">

**Author:** ![mkitti](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mkitti/32/12459_2.png) [@mkitti](https://discourse.julialang.org/u/mkitti)\
**Post date:** [January 4, 2023, 4:34pm UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/31 "2023-01-04T16:34:17Z")

</div>

> [@mit.edelman](#):
>
> stack is nice but Matrix is better, can we have both?  
> I wish almost every data structure could be "Matrix"ified to some default  
> even if it’s not what every user would want

I understand that you were an early user of MATLAB. 🙂 . Below is what you basically want, right?

```julia
julia> Base.Matrix(vv::Vector{Vector{T}}) where T = hcat(vv...)

julia> Base.Matrix(vm::Vector{Matrix{T}}) where T = vcat(vm...)

julia> Matrix([[1,2], [3, 4], [5, 6]])
2×3 Matrix{Int64}:
 1 3 5
 2 4 6

julia> Matrix([[1 2], [3 4], [5 6]])
3×2 Matrix{Int64}:
 1 2
 3 4
 5 6

julia> Matrix([[1 2 3], [3 4], [5 6]])
ERROR: ArgumentError: number of columns of each array must match (got (3, 2, 2))
...

julia> Matrix([[1, 2], [3, 4], [5, 6, 7]])
ERROR: DimensionMismatch: vectors must have same lengths
Stacktrace:
...

```

---

<div class="post-metadata">

**Author:** ![mit.edelman](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mit.edelman/32/18467_2.png) [@mit.edelman](https://discourse.julialang.org/u/mit.edelman)\
**Post date:** [January 4, 2023, 4:45pm UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/32 "2023-01-04T16:45:41Z")

</div>

yup  
and this has nothing to do with Matlab and everything to do with ease of use

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [January 4, 2023, 5:32pm UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/33 "2023-01-04T17:32:31Z")

</div>

> [@mkitti](#):
>
> ```julia
> julia> Base.Matrix(vv::Vector{Vector{T}}) where T = hcat(vv...)
> 
> julia> Base.Matrix(vm::Vector{Matrix{T}}) where T = vcat(vm...)
> 
> ```

This combination seems pretty confusing to me. If you have a vector of vectors they are stacked horizontally, but if you have a vector of 1-column matrices they are stacked vertically?

A compromise would be to simply throw a more informative error:

```julia
Matrix(::AbstractVector{<:AbstractArray}) =
     throw(ArgumentError("Matrix(...) does not support vectors of arrays; perhaps you mean stack(...)?"))
```

---

<div class="post-metadata">

**Author:** ![DNF](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dnf/32/10191_2.png) [@DNF](https://discourse.julialang.org/u/DNF)\
**Post date:** [January 4, 2023, 5:40pm UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/34 "2023-01-04T17:40:51Z")

</div>

> [@sijo](#):
>
> Define a **function** (with name in lowercase) for more complex operations. The function does the heavy work and eventually calls a constructor to create the instance.

This seems like the right way. Convenience functions like the requested could be a function `matrix` (lowercase), defined in the user’s own startup.jl, or maybe in a Convenience.jl package.

---

<div class="post-metadata">

**Author:** ![mkitti](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mkitti/32/12459_2.png) [@mkitti](https://discourse.julialang.org/u/mkitti)\
**Post date:** [January 5, 2023, 7:00am UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/35 "2023-01-05T07:00:57Z")

</div>

> [@stevengj](#):
>
> This combination seems pretty confusing to me. If you have a vector of vectors they are stacked horizontally, but if you have a vector of 1-column matrices they are stacked vertically?

The idea was to stack row vectors (1xN matrices) vertically. That’s the inherent flaw in this though is that there is an ambiguity in both cases of how one wants to concatenate. I suppose we could take a dims parameter and just forward to `cat`.

We could then generalize this so that one could convert of a Vector of n-dimensional Arrays to a n+1 dimensional array.

```julia
julia> const NArray{N} = Array{T,N} where T
Array{T, N} where {N, T}

julia> function (NArray{N})(vector_of_arrays::Vector{Array{T,M}}; dims = 1) where {T, N,M}
           M <= N || throw(MethodError(NArray{N}, (vector_of_arrays,)))
           A = cat(vector_of_arrays...; dims)
           reshape(A, ntuple(i->i <= ndims(A) ? size(A,i) : 1,N))
       end

julia> Matrix([[1 2], [3 4], [5 6]])
3×2 Matrix{Int64}:
 1 2
 3 4
 5 6

julia> Matrix([[1 2], [3 4], [5 6]]; dims=2)
1×6 Matrix{Int64}:
 1 2 3 4 5 6

julia> NArray{3}([[1, 2], [3, 4], [5, 6]]; dims=1)
6×1×1 Array{Int64, 3}:
[:, :, 1] =
 1
 2
 3
 4
 5
 6

julia> NArray{3}([[1, 2], [3, 4], [5, 6]]; dims=2)
2×3×1 Array{Int64, 3}:
[:, :, 1] =
 1 3 5
 2 4 6

julia> NArray{3}([[1, 2], [3, 4], [5, 6]]; dims=3)
2×1×3 Array{Int64, 3}:
[:, :, 1] =
 1
 2

[:, :, 2] =
 3
 4

[:, :, 3] =
 5
 6

julia> NArray{3}([[1 2], [3 4], [5 6]]; dims=3)
1×2×3 Array{Int64, 3}:
[:, :, 1] =
 1 2

[:, :, 2] =
 3 4

[:, :, 3] =
 5 6

julia> NArray{3}([[1 2], [3 4], [5 6]]; dims=1)
3×2×1 Array{Int64, 3}:
[:, :, 1] =
 1 2
 3 4
 5 6

julia> NArray{3}([[1 2], [3 4], [5 6]]; dims=2)
1×6×1 Array{Int64, 3}:
[:, :, 1] =
 1 2 3 4 5 6

julia> NArray{0}(x::T) where T = fill!(NArray{0}{T}(undef),x)

julia> Vector([NArray{0}(6), NArray{0}(3)])
2-element Vector{Int64}:
 6
 3

```

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [January 5, 2023, 12:46pm UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/36 "2023-01-05T12:46:10Z")

</div>

> [@mkitti](#):
>
> We could then generalize this so that one could convert of a Vector of n-dimensional Arrays to a n+1 dimensional array.

That’s what the `stack` function already does.

---

<div class="post-metadata">

**Author:** ![PaulN](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pauln/32/47997_2.png) [@PaulN](https://discourse.julialang.org/u/PaulN)\
**Post date:** [April 4, 2023, 3:49pm UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/37 "2023-04-04T15:49:15Z")

</div>

It’s perhaps not elegant, but how about this:

“”"

# Convert a vector of vectors to an array

This function assumes that each vector is the same length;  
i.e.  
v1 = [[1,2], [2,3], [5,6] ] # this is fine  
v2 = [[1,2,8], [2,3], [5,6] ] # this is not fine

Example of usage:

```julia-auto
vv = [[1,2,3], [4,5,6], [7,8,9],[12,13,14]]
println("num components in each vector = ", length(vv[1]))
println("num of vectors = ", length(vv))
vecvec_to_array(vv)

```

“”"

```julia
function vecvec_to_array(vecvec)
    dim1 = length(vecvec)
    dim2 = length(vecvec[1])
    my_array = zeros(Int64, dim1, dim2)
    for i in 1:dim1
        for j in 1:dim2
            my_array[i,j] = vecvec[i][j]
        end
    end
    return my_array
end

```

---

<div class="post-metadata">

**Author:** ![marianoarnaiz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/marianoarnaiz/32/19377_2.png) [@marianoarnaiz](https://discourse.julialang.org/u/marianoarnaiz)\
**Post date:** [December 8, 2023, 1:43pm UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/38 "2023-12-08T13:43:51Z")

</div>

Any way to do exactly the opposite? from matrix to a vector of vectors

---

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [December 8, 2023, 1:51pm UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/39 "2023-12-08T13:51:20Z")

</div>

```julia
eachrow()
eachcol()

```

---

<div class="post-metadata">

**Author:** ![marianoarnaiz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/marianoarnaiz/32/19377_2.png) [@marianoarnaiz](https://discourse.julialang.org/u/marianoarnaiz)\
**Post date:** [December 8, 2023, 7:57pm UTC](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609/40 "2023-12-08T19:57:34Z")

</div>

Thanks!

[Previous page](https://discourse.julialang.org/t/how-to-convert-vector-of-vectors-to-matrix/72609.md?page=1)
