在 Julia 中从 python 替代 np.meshgrid()?

Alternate to np.meshgrid() from python in Julia?

我想知道,在 Julia 中,是否有替代 NumPy-Python 的 np.meshgrid() 的方法?

#Python 参考:https://numpy.org/doc/stable/reference/generated/numpy.meshgrid.html

按照 Julia 中 Python meshgrid 手册中的示例,您可以执行以下操作:

x = 0.0:0.5:1.0   
y = 0.0:1.0

julia> xv = first.(Iterators.product(x,y))
3×2 Matrix{Float64}:
 0.0  0.0
 0.5  0.5
 1.0  1.0

julia> yv = last.(Iterators.product(x,y))
3×2 Matrix{Float64}:
 0.0  1.0
 0.0  1.0
 0.0  1.0

这些结果是转置的(与 Python 相比),但在 Julia 中,与 Python 相反,第一个数组索引是行,第二个是列(Julia 有列优先数组)

请记住,在 Julia 中,您通常可以避免 meshgrid 使用智能广播操作。例如。给定一个对标量值和两个“向量”xsys 进行运算的函数 f(x, y),您可以编写 f.(xs, ys') 来产生几乎任何 meshgrid 会产生的结果给你更多:

julia> xs = 0:0.5:1
0.0:0.5:1.0

julia> ys = 0.0:1.0
0.0:1.0:1.0

julia> f(x, y) = (x, y)                # equivalent to meshgrid
f (generic function with 1 method)

julia> f.(xs, ys')
3×2 Matrix{Tuple{Float64, Float64}}:
 (0.0, 0.0)  (0.0, 1.0)
 (0.5, 0.0)  (0.5, 1.0)
 (1.0, 0.0)  (1.0, 1.0)

julia> g(x, y) = x*y                   # more efficient than meshgrid + product
g (generic function with 1 method)

julia> g.(xs, ys')
3×2 Matrix{Float64}:
 0.0  0.0
 0.0  0.5
 0.0  1.0