Since Julia 1.9.0 stack
can be used to combine a collection of arrays (or other iterable objects) of equal size into one larger array, by arranging them along one or more new dimensions so it can be used to construct a matrix from row/column vectors (returned from function/expression). For versions before 1.9.0 it can be activated with using Compat
.
column(j) = [j, j, j]
stack(column(j) for j=1:4)
#3×4 Matrix{Int64}:
# 1 2 3 4
# 1 2 3 4
# 1 2 3 4
What is fast and memory efficient.
using BenchmarkTools
column(j) = [j, j, j]
@btime stack(column(j) for j=1:4)
# 193.315 ns (5 allocations: 480 bytes)
#3×4 Matrix{Int64}:
# 1 2 3 4
# 1 2 3 4
# 1 2 3 4
@btime begin #@Benoît Legat
m = Matrix{Int}(undef, 3, 4)
for j in 1:4
m[:, j] = column(j)
end
m
end
# 201.942 ns (5 allocations: 480 bytes)
#3×4 Matrix{Int64}:
# 1 2 3 4
# 1 2 3 4
# 1 2 3 4
@btime reduce(hcat, [column(j) for j=1:4]) #@Przemyslaw Szufel
# 249.676 ns (6 allocations: 560 bytes)
#3×4 Matrix{Int64}:
# 1 2 3 4
# 1 2 3 4
# 1 2 3 4
@btime reshape(collect(Iterators.flatten([column(j) for j in 1:4])), 3, 4) #@Benoît Legat
# 392.325 ns (10 allocations: 976 bytes)
#3×4 Matrix{Int64}:
# 1 2 3 4
# 1 2 3 4
# 1 2 3 4
@btime Int[column(j)[i] for i in 1:3, j in 1:4] #@radioflash
# 440.211 ns (13 allocations: 1.09 KiB)
#3×4 Matrix{Int64}:
# 1 2 3 4
# 1 2 3 4
# 1 2 3 4
@btime hcat([column(j) for j=1:4]...) #@spencerlyon2
# 644.676 ns (10 allocations: 784 bytes)
#3×4 Matrix{Int64}:
# 1 2 3 4
# 1 2 3 4
# 1 2 3 4
In case you have already a vector.
c = [[j,j,j] for j in 1:4]
#4-element Vector{Vector{Int64}}:
# [1, 1, 1]
# [2, 2, 2]
# [3, 3, 3]
# [4, 4, 4]
stack(c)
#3×4 Matrix{Int64}:
# 1 2 3 4
# 1 2 3 4
# 1 2 3 4
using BenchmarkTools
@btime stack($c)
# 63.204 ns (1 allocation: 160 bytes)
#3×4 Matrix{Int64}:
# 1 2 3 4
# 1 2 3 4
# 1 2 3 4
@btime reduce(hcat, $c) #@Przemyslaw Szufel
# 68.758 ns (1 allocation: 160 bytes)
#3×4 Matrix{Int64}:
# 1 2 3 4
# 1 2 3 4
# 1 2 3 4
@btime begin #@Benoît Legat
m = Matrix{Int}(undef, 3, 4)
for j in 1:4
m[:, j] = $c[j]
end
m
end
# 75.586 ns (1 allocation: 160 bytes)
#3×4 Matrix{Int64}:
# 1 2 3 4
# 1 2 3 4
# 1 2 3 4
@btime reshape(collect(Iterators.flatten($c)), 3, 4) #@Benoît Legat
# 210.752 ns (5 allocations: 576 bytes)
#3×4 Matrix{Int64}:
# 1 2 3 4
# 1 2 3 4
# 1 2 3 4
@btime hcat($c...) #@spencerlyon2
# 453.213 ns (5 allocations: 384 bytes)
#3×4 Matrix{Int64}:
# 1 2 3 4
# 1 2 3 4
# 1 2 3 4