# Cartesian Product Iterator from a Matrix

**URL:** <https://discourse.julialang.org/t/cartesian-product-iterator-from-a-matrix/90066>\
**Category:** New to Julia\
**Created:** [November 10, 2022, 6:53pm UTC](https://discourse.julialang.org/t/cartesian-product-iterator-from-a-matrix/90066 "2022-11-10T18:53:11Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Mark\_Williams](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mark_williams/32/7668_2.png) [@Mark\_Williams](https://discourse.julialang.org/u/Mark_Williams)\
**Post date:** [November 10, 2022, 6:53pm UTC](https://discourse.julialang.org/t/cartesian-product-iterator-from-a-matrix/90066/1 "2022-11-10T18:53:11Z")

</div>

I would like to take a matrix, A, and iterate over the Cartesian product of its entries. I can easily do this by

```julia
for (a,b,c) in Iterators.product(A[:,1], A[:,2], A[:,3])
    println("$a, $b, $c")
end 

```

But what I would ideally like is something along the lines of

```julia
for (a,b,c,...) in Iterators.product(for col in eachcol(A))
    println("$a, $b, $c,...")
end 

```

(which obviously doesn’t work but you get the idea I hope) for an N by N matrix. I don’t know if this is even possible. If anyone can provide some advice I would be very grateful.

---

<div class="post-metadata">

**Author:** ![goerch](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/goerch/32/29122_2.png) [@goerch](https://discourse.julialang.org/u/goerch)\
**Post date:** [November 10, 2022, 7:37pm UTC](https://discourse.julialang.org/t/cartesian-product-iterator-from-a-matrix/90066/2 "2022-11-10T19:37:11Z")

</div>

Does something like

```julia
for x in Iterators.product(eachcol(A)...)
    println("$x")
end 

```

help?

---

<div class="post-metadata">

**Author:** ![cgeoga](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/cgeoga/32/216186_2.png) [@cgeoga](https://discourse.julialang.org/u/cgeoga)\
**Post date:** [November 10, 2022, 7:43pm UTC](https://discourse.julialang.org/t/cartesian-product-iterator-from-a-matrix/90066/3 "2022-11-10T19:43:50Z")

</div>

Does it need to be in column order? Here’s a very simple thing that might be giving what you want:

```julia
va = vec(A)
for (aj, ak) in Iterators.product(va, va)
  [...]
end

```

If you do want something that specifically works with columns, it might be worth considering doing something that is readable and easy like

```julia
col_range = 1:size(A,2)
for (j, k) in Iterators.product(1:col_range, 1:col_range)
  cj = A[:,j]
  ck = A[:,k]
  [...]
end

```
