This is implemented in QuantEcon
using QuantEcon, DataFrames
julia> DataFrame(gridmake([1,2,3], [4,5,6]))
9Γ2 DataFrame
β Row β x1 β x2 β
βββββββΌβββββΌβββββ€
β 1 β 1 β 4 β
β 2 β 2 β 4 β
β 3 β 3 β 4 β
β 4 β 1 β 5 β
β 5 β 2 β 5 β
β 6 β 3 β 5 β
β 7 β 1 β 6 β
β 8 β 2 β 6 β
β 9 β 3 β 6 β
QuantEcon is available for β₯ 0.6 (includes 1.0). If you donβt want to use the package, my suggested implementation is
function gridmake(arrays::AbstractVecOrMat...)
l = size.(arrays, 1)
nrows = prod(l)
output = mapreduce(a_o -> repeat(a_o[1],
inner = (a_o[2], 1),
outer = (div(nrows, size(a_o[1], 1) * a_o[2]), 1)),
hcat,
zip(arrays, cumprod(prepend!(collect(l[1:end - 1]), 1))))
return output
end
Note: Many of the implementations suggested above only work for AbstractVector
and give the wrong result for AbstractMatrix
. As a test case you can use,
using QuantEcon: gridmake
using BenchmarkTools: @btime
const x, y, z = 1:3, [10 20; 30 40], [100, 200];
arrays = [x, y, z];
# Here goes the implementation call it magic
magic(arrays...) == gridmake(arrays...) # They match
@btime magic($arrays...) # Check efficiency