# Meshgrid function in Julia

**URL:** <https://discourse.julialang.org/t/meshgrid-function-in-julia/48679>\
**Category:** Numerics\
**Created:** [October 20, 2020, 12:36pm UTC](https://discourse.julialang.org/t/meshgrid-function-in-julia/48679 "2020-10-20T12:36:30Z")\
**Posts on this page:** 1\
**Showing post:** 26

<div class="post-metadata">

**Author:** ![henry2004y](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/henry2004y/32/9284_2.png) [@henry2004y](https://discourse.julialang.org/u/henry2004y)\
**Post date:** [June 27, 2021, 8:00am UTC](https://discourse.julialang.org/t/meshgrid-function-in-julia/48679/26 "2021-06-27T08:00:55Z")

</div>

> [@Ionizing](#):
>
> ```julia
> x = 1:3;
> y = 4:6;
> 
> ```

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

```julia
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:

```julia
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
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)

```

---

_[View the full topic](https://discourse.julialang.org/t/meshgrid-function-in-julia/48679)._
