Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Convert a vector of vectors to a matrix

Use the stack function.

stack([[1,0,1],[0,0,1]], dims=1) == [ 1 0 1 ; 0 0 1 ]
true

If you only need broadcast operations, RecursiveArrayTools.jl wraps a vector of vectors.

using RecursiveArrayTools

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
vA = VectorOfArray(a)
vB = VectorOfArray(b)

vA .* vB
VectorOfArray{Int64,2}: 3-element Vector{Vector{Int64}}: [1, 4, 9] [16, 25, 36] [49, 64, 81]

Convert a VectorOfArray into a matrix.

Matrix(vA .* vB)
3×3 Matrix{Int64}: 1 16 49 4 25 64 9 36 81
x = rand((7, 10))
CI = CartesianIndices((7, 10))
for i in 1:length(x)
    r = CI[i][1]
    c = CI[i][2]
    @assert x[i] == x[r, c]
end

This notebook was generated using Literate.jl.