Reproduce the `expand.grid` function from R in Julia
Thanks to @Henrik's comment:
x = [1,2,3]
y = ["a","b"]
z = [10,12]
d = collect(Iterators.product(x,y,z))
Here is another solution using list comprehension
reshape([ [x,y,z] for x=x, y=y, z=z ],length(x)*length(y)*length(z))
Here is my completely(?) general solution, using recursion, varargs, and splatting:
function expandgrid(args...)
if length(args) == 0
return Any[]
elseif length(args) == 1
return args[1]
else
rest = expandgrid(args[2:end]...)
ret = Any[]
for i in args[1]
for r in rest
push!(ret, vcat(i,r))
end
end
return ret
end
end
eg = expandgrid([1,2,3], ["a","b"], [10,12])
@assert length(eg) == 3*2*2
@show eg
This gives an array of arrays, but you could combine that into a matrix trivially if thats what you wanted.