朱莉娅中两个向量的笛卡尔积

P. *_*eri 7 cartesian-product julia

我有两个矢量xy,各自的长度n和p的.是否有内置的方法来创建一个np x 2矩阵

x[1] y[1]
x[1] y[2]
...
x[1] y[p]
x[2] y[1]
...
x[n] y[p]
Run Code Online (Sandbox Code Playgroud)

我可以用嵌套的for循环来做到这一点,但我正在寻找一个内置函数,如果它存在的话.

Mat*_*ský 9

至少在 Julia 1.3 中,有一个内置函数 Iterators.product,所以 Iterators.product(a, b) |> collect应该这样做。

  • 请注意,“Iterators”是 Julia 的“Base”模块(“Base.Iterators”)的一部分,因此您根本不必调用“import”或“using”即可使用“Iterators.product”。 (2认同)

Est*_*ban 7

Julia通常在嵌套循环中非常快,所以如果它们对你正常工作,你应该可以检查性能,或者只是坚持下去.

其他选项是使用repmat(这个比使用repeat更快一点):

[repmat(x,1,length(y))'[:] repmat(y,length(x),1)[:]]
Run Code Online (Sandbox Code Playgroud)

对这两种方法进行了一些快速测试:

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)
Run Code Online (Sandbox Code Playgroud)

不知道为什么这么大的差异,我认为还有改进的余地.没有尝试过Iterators.jl包中的产品功能.

还有更多信息:https://groups.google.com/forum/#!topic/julia-users/dtl--SyFgwY

希望这可以帮助.

尝试了几个嵌套循环,确实更快:

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
Run Code Online (Sandbox Code Playgroud)

而且,rand(1000)对于xy.

withloops(x,y)
elapsed time: 0.011350679 seconds (16000128 bytes allocated)
Run Code Online (Sandbox Code Playgroud)


spe*_*on2 5

这是我可能的方法:

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
Run Code Online (Sandbox Code Playgroud)

您可能还想看看Iterators.j-特别是该product函数。


小智 5

这在IterTools模块中提供(它取代了Iterators模块).

取自https://github.com/JuliaCollections/IterTools.jl

迭代输入的笛卡尔积中的所有组合.

例:

using IterTools
for p in product(1:3,1:2)
    @show p
end

p = (1,1)
p = (2,1)
p = (3,1)
p = (1,2)
p = (2,2)
p = (3,2)
Run Code Online (Sandbox Code Playgroud)