首页 > 解决方案 > 在 Julia 中从 python 替代 np.meshgrid()?

问题描述

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

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

标签: numpyjuliamesh

解决方案


请记住,在 Julia 中,您通常可以避免meshgrid使用智能广播操作。例如。f(x, y)给定一个对标量值和两个“向量”xs和进行操作的函数ys,您可以编写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

推荐阅读