# Create matrix by combining vectors element-wise

**URL:** <https://discourse.julialang.org/t/create-matrix-by-combining-vectors-element-wise/80373>\
**Category:** New to Julia\
**Tags:** arrays\
**Created:** [May 2, 2022, 3:34pm UTC](https://discourse.julialang.org/t/create-matrix-by-combining-vectors-element-wise/80373 "2022-05-02T15:34:56Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![jacobusmmsmit](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jacobusmmsmit/32/217669_2.png) [@jacobusmmsmit](https://discourse.julialang.org/u/jacobusmmsmit)\
**Post date:** [May 2, 2022, 4:10pm UTC](https://discourse.julialang.org/t/create-matrix-by-combining-vectors-element-wise/80373/2 "2022-05-02T16:10:20Z")

</div>

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:

```julia
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

---

_[View the full topic](https://discourse.julialang.org/t/create-matrix-by-combining-vectors-element-wise/80373)._
