# Combvec in Julia

Sorry I have a trivial question. In matlab, `combvec` takes as inputs vectors and outputs all combinations of element from each vector. I was looking for a similar function in julia and found one in the SparseGrids library. I expect the following code to yield an array of vectors.

``````using SparseGrids
A = Vector(0:1)
vectorCombs = SparseGrids.combvec(A,A,A)
``````

However I receive the following error:

``````ERROR: MethodError: no method matching combvec(::Vector{Int64})
Closest candidates are:
combvec(::Array{Vector{T}, 1}) where T at ~/.julia/packages/SparseGrids/P8oxX/src/grids.jl:158
Stacktrace:
 top-level scope
@ REPL:1
``````

I loaded the library, what happened?

You might want `Iterators.product`

``````julia> a = collect(0:5);

julia> collect(Iterators.product(a, a))
6×6 Matrix{Tuple{Int64, Int64}}:
(0, 0)  (0, 1)  (0, 2)  (0, 3)  (0, 4)  (0, 5)
(1, 0)  (1, 1)  (1, 2)  (1, 3)  (1, 4)  (1, 5)
(2, 0)  (2, 1)  (2, 2)  (2, 3)  (2, 4)  (2, 5)
(3, 0)  (3, 1)  (3, 2)  (3, 3)  (3, 4)  (3, 5)
(4, 0)  (4, 1)  (4, 2)  (4, 3)  (4, 4)  (4, 5)
(5, 0)  (5, 1)  (5, 2)  (5, 3)  (5, 4)  (5, 5)
``````

Iterators is in Base, so you don’t need to install it.

bleh, thx

Also, note that the error you posted suggests that the method `combvec` expects to take an `Array{T, 1}` of `Vectors` – also known as a `Vector{Vector{T}}`.

``````julia> using SparseGrids
julia> A = Vector(0:1)
2-element Vector{Int64}:
0
1

julia> vectorCombs = SparseGrids.combvec([A,A,A])
8-element Vector{Vector{Int64}}:
[0, 0, 0]
[1, 0, 0]
[0, 1, 0]
[1, 1, 0]
[0, 0, 1]
[1, 0, 1]
[0, 1, 1]
[1, 1, 1]
``````

And yes, it does use `Iterators.product`: SparseGrids.jl/grids.jl at d4fca5258321657542143773cd0763d2f03a8b50 · robertdj/SparseGrids.jl · GitHub

1 Like