在 Julia 中生成直线网格坐标

Tim*_*mmm 3 julia

在 Julia 中,制作这样的 (X, Y) 数组的最佳方法是什么?

0 0
1 0
2 0
3 0
0 1
1 1
2 1
3 1
0 2
1 2
2 2
3 2
0 3
1 3
2 3
3 3
Run Code Online (Sandbox Code Playgroud)

坐标是规则的和直线的,但不一定是整数。

tim*_*tim 5

Julia 0.6 包含一个高效的product迭代器,它允许第四个解决方案。比较所有解决方案:

using Base.Iterators

f1(xs, ys) = [[xs[i] for i in 1:length(xs), j in 1:length(ys)][:] [ys[j] for i in 1:length(xs), j in 1:length(ys)][:]]
f2(xs, ys) = hcat(repeat(xs, outer=length(ys)), repeat(ys, inner=length(xs)))
f3(xs, ys) = vcat(([x y] for y in ys for x in xs)...)
f4(xs, ys) = (eltype(xs) == eltype(ys) || error("eltypes must match"); 
                reinterpret(eltype(xs), collect(product(xs, ys)), (2, length(xs)*length(ys)))')

xs = 1:3
ys = 0:4

@show f1(xs, ys) == f2(xs, ys) == f3(xs, ys) == f4(xs, ys)

using BenchmarkTools

@btime f1($xs, $ys)
@btime f2($xs, $ys)
@btime f3($xs, $ys)
@btime f4($xs, $ys)
Run Code Online (Sandbox Code Playgroud)

在我的电脑上,这会导致:

f1(xs, ys) == f2(xs, ys) == f3(xs, ys) == f4(xs, ys) = true
  548.508 ns (8 allocations: 1.23 KiB)
  3.792 ?s (49 allocations: 2.45 KiB)
  1.916 ?s (51 allocations: 3.17 KiB)
  353.880 ns (8 allocations: 912 bytes)
Run Code Online (Sandbox Code Playgroud)

对于xs = 1:300ys=0:400我得到:

f1(xs, ys) == f2(xs, ys) == f3(xs, ys) == f4(xs, ys) = true
  1.538 ms (13 allocations: 5.51 MiB)
  1.032 ms (1636 allocations: 3.72 MiB)
  16.668 ms (360924 allocations: 24.95 MiB)
  927.001 ?s (10 allocations: 3.67 MiB)
Run Code Online (Sandbox Code Playgroud)

编辑:

到目前为止,最快的方法是对预先分配的数组进行直接循环:

function f5(xs, ys)
    lx, ly = length(xs), length(ys)
    res = Array{Base.promote_eltype(xs, ys), 2}(lx*ly, 2)
    ind = 1
    for y in ys, x in xs
        res[ind, 1] = x
        res[ind, 2] = y
        ind += 1
    end
    res
end
Run Code Online (Sandbox Code Playgroud)

对于xs = 1:3ys = 0:4f5需要65.339 ns (1 allocation: 336 bytes)

对于xs = 1:300ys = 0:400,需要280.852 ?s (2 allocations: 1.84 MiB)

编辑2:

包括f6来自 Dan Getz 的评论:

function f6(xs, ys)
    lx, ly = length(xs), length(ys)
    lxly = lx*ly
    res = Array{Base.promote_eltype(xs, ys), 2}(lxly, 2)
    ind = 1
    while ind<=lxly
        @inbounds for x in xs
            res[ind] = x
            ind += 1
        end
    end
    for y in ys
        @inbounds for i=1:lx
        res[ind] = y
        ind += 1
        end
    end
    res
end
Run Code Online (Sandbox Code Playgroud)

通过尊重 Julia 数组的列优先顺序,它将时间分别减少到47.452 ns (1 allocation: 336 bytes)171.709 ?s (2 allocations: 1.84 MiB)