Meshgrid function in Julia

To get meshgrid style, x and y shall be swapped as

xv = getindex.(Iterators.product(y, x, z), 2)
yv = getindex.(Iterators.product(y, x, z), 1)

However, if you really need this, by far the easiest and fastest I’ve tested is list comprehension:

function meshgrid(x, y)
   X = [x for _ in y, x in x]
   Y = [y for y in y, _ in x]
   X, Y
end

function meshgrid2(x, y)
   X = getindex.(Iterators.product(y, x), 2)
   Y = getindex.(Iterators.product(y, x), 1)
   X, Y
end

x = 1:1000
y = 1001:2000
julia> @time meshgrid(x,y);
  0.007225 seconds (5 allocations: 15.259 MiB)

julia> @time meshgrid2(x,y);
  0.028644 seconds (9 allocations: 45.777 MiB, 18.41% gc time)

julia> @btime meshgrid($x,$y);
  1.033 ms (4 allocations: 15.26 MiB)

julia> @btime meshgrid2($x,$y);
  4.810 ms (8 allocations: 45.78 MiB)