Julia中两个向量的笛卡尔积

Julia中两个向量的笛卡尔积,julia,cartesian-product,Julia,Cartesian Product,我有两个向量x和y,分别长度为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] 我可以用嵌套的for循环来实现这一点,但我正在寻找一个内置函数,如果它存在的话。我可以这样做: julia> x = [1, 2, 3, 4]; julia> y = [9, 8, 7]; julia> [repeat(x, inner=[size(y,1)]) repeat(

我有两个向量
x
y
,分别长度为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]

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

我可以这样做:

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

您可能还想看一看,特别是
产品
函数。

Julia在嵌套循环中通常速度非常快,因此,如果它们对您正常工作,您应该检查性能,也许可以坚持使用它

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

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

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)
不知道为什么会有这么大的差异,我认为还有改进的余地。 尚未尝试Iterators.jl包中的product函数

这里还有更多的信息:

希望这有帮助

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

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
对于相同的
rand(1000)
,对于
x
y

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

这在IterTools模块(它取代了迭代器模块)中提供

取自

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

例如:

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)

至少在Julia 1.3中,有一个内置函数Iterators.product,所以
Iterators.product(a,b)|>collect
应该可以。
@inbounds
是否有助于
for
循环?@rickhg12hs应该是的,我发布它时有点匆忙,所以我没有时间进行适当的测试,但我明天会做,并相应地编辑帖子。谢谢你的建议。我试着使用
@inbounds
,但没有得到任何明显的改进,也许这是因为没有对数组进行操作,而我只是赋值?此外,在我的计算机中,使用长度为10000的向量作为
x
y
的输入,在使用
repeat
repmat
时会产生内存错误,但嵌套循环函数运行良好。请注意,可以省略
内部
外部
参数周围的括号,因此,公式简化为重复(x,内部=大小(y,1))重复(y,外部=大小(x,1))
我不确定它是否替换迭代器模块,因为在julia 1.3rc4中使用IterTools.product时,它说它不赞成使用迭代器。产品此解决方案在我使用Julia 1.5时运行得更快。请注意,
迭代器
是Julia的
Base
模块(
Base.Iterators
)的一部分,因此您不必调用
导入
使用
就可以使用
迭代器。产品
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)