Cartesian product of two vectors in Julia

I have two vectors x and y corresponding lengths n and p. Is there a built-in way to create an np x 2 matrix that will

 x[1] y[1] x[1] y[2] ... x[1] y[p] x[2] y[1] ... x[n] y[p] 

I can do this with a nested loop, but I'm looking for a built-in function, if it exists.

+6
source share
3 answers

Julia is usually very fast in nested loops, so if they work correctly for you, you should control the performance, maybe just stick to it.

Another option would be to use repmat (this is slightly faster than using repeat):

 [repmat(x,1,length(y))'[:] repmat(y,length(x),1)[:]] 

Was there a quick test of both methods:

 x=rand(1000) y=rand(1000) function withrepeat(x,y) [repeat(x, inner=[size(y,1)]) repeat(y, outer=[size(x,1)])] end function withrepmat(x,y) [repmat(x,1,length(y))'[:] repmat(y,length(x),1)[:]] end withrepeat(x,y) elapsed time: 0.21556302 seconds (95986112 bytes allocated) with repmat(x,y) elapsed time: 0.075604488 seconds (56000560 bytes allocated) 

Not sure why there is so much difference, and I think there is still room for improvement. They did not try to use the product function inside the Iterators.jl package.

Also a bit more info here: https://groups.google.com/forum/#!topic/julia-users/dtl--SyFgwY

Hope this helps.

Tried a couple of nested loops and really faster:

 function withloops (x,y) leny=length(y) lenx=length(x) m=leny*lenx OUT = zeros(Float64, m,2) c=1 for i = 1:lenx for j = 1:leny OUT[c,1] = x[i] OUT[c,2] = y[j] c+=1 end end return OUT end 

And for the same rand(1000) for x and y .

 withloops(x,y) elapsed time: 0.011350679 seconds (16000128 bytes allocated) 
+6
source

Here's how I can do it:

 julia> x = [1, 2, 3, 4]; julia> y = [9, 8, 7]; julia> [repeat(x, inner=[size(y,1)]) repeat(y, outer=[size(x,1)])] 12x2 Array{Int64,2}: 1 9 1 8 1 7 2 9 2 8 2 7 3 9 3 8 3 7 4 9 4 8 4 7 

you can also take a look at Iterators.j - specifically, the product function.

+4
source

This is provided in the Iterators module.

Taken from https://github.com/JuliaLang/Iterators.jl

Iterates over all combinations in the Cartesian product of inputs.

Example:

 for p in product(1:3,1:2) @show p end yields p = (1,1) p = (2,1) p = (3,1) p = (1,2) p = (2,2) p = (3,2) 
+3
source

Source: https://habr.com/ru/post/984439/


All Articles