Create matrix by combining vectors element-wise

You’re generating the cartesian product of the two vectors which we can do with Iterators.product. Depending on what you want to do with this object afterwards, you may not need to call collect afterwards, but if you’re dead set on having it be a two column matrix then we can use reinterpret to minimise allocations and be ultra-performant.

The following code does what you want and is very fast:

reshape(reinterpret(Int, collect(Iterators.product(a, b))), (2, :))'

using BenchmarkTools
a = [1, 2, 3]
b = [4, 5]

@btime reshape(reinterpret(Int, collect(Iterators.product($a, $b))), (2, :))'
> 52.077 ns (1 allocation: 160 bytes)

Note the return type is not a Matrix, but it can be used as one (or you can make it one by calling stuff |> Matrix but you really shouldn’t need to).

Edit: cleaner solution and benchmark

3 Likes