在Julia中生成直线网格坐标

时间:2017-05-09 09:38:49

标签: 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

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

3 个答案:

答案 0 :(得分:4)

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)

在我的电脑上,结果是:

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)

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)

修改

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

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

对于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:

包括Dan Getz的f6评论:

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

通过尊重Julia数组的列主要顺序,它会将时间分别缩短为47.452 ns (1 allocation: 336 bytes)171.709 μs (2 allocations: 1.84 MiB)

答案 1 :(得分:2)

这似乎可以解决问题。不确定它是最好的解决方案。似乎有点费解。

<mvc:resources mapping="/images/**" location="/images/" />

答案 2 :(得分:1)

听起来像repeat的工作: hcat(repeat(0:3, outer=4), repeat(0:3, inner=4))

请注意,当xsys较小时(例如330),它比数组理解慢得多。