Mesh (ndgrid) to points list

Is there any quick method to generate position pairs (x,y) for each points from following mesh grid xg and yg?

x = range(-2, 2, 50)
y = range(-2, 2, 50)
(xg, yg) = ndgrid(x, y)

Finished with collect(zip(xg,yg))

x = range(-2, 2, 50)
y = range(-2, 2, 50)

# Scheme 1
xg = zeros(50 * 50)
yg = zeros(50 * 50)
for i = 1:50, j = 1:50
    xg[(i-1)*50+j] = x[i]
    yg[(i-1)*50+j] = y[j]
end

# Scheme 2
g = ((xg, yg) for xg in x, yg in y)
collect(g) # 50×50 Matrix{Tuple{Float64, Float64}}

This question has been answered multiple times in the forum.

Here is another solution with broadcasting:

f(x, y) = (x, y)

f.(xs, ys')
1 Like

There’s also Iterators.product, with or without collect (usually without, if you can help it), which is essentially the same as the ((xg, yg) for xg in x, yg in y) solution above but easier to write in an abitrary number of dimensions.

julia> collect(Iterators.product(x, y))
50×50 Matrix{Tuple{Float64, Float64}}:
 (-2.0, -2.0)      (-2.0, -1.91837)      …  (-2.0, 1.91837)      (-2.0, 2.0)
 (-1.91837, -2.0)  (-1.91837, -1.91837)     (-1.91837, 1.91837)  (-1.91837, 2.0)
 (-1.83673, -2.0)  (-1.83673, -1.91837)     (-1.83673, 1.91837)  (-1.83673, 2.0)
 (-1.7551, -2.0)   (-1.7551, -1.91837)      (-1.7551, 1.91837)   (-1.7551, 2.0)
 (-1.67347, -2.0)  (-1.67347, -1.91837)     (-1.67347, 1.91837)  (-1.67347, 2.0)
 (-1.59184, -2.0)  (-1.59184, -1.91837)  …  (-1.59184, 1.91837)  (-1.59184, 2.0)
 ⋮                                       ⋱
 (1.67347, -2.0)   (1.67347, -1.91837)   …  (1.67347, 1.91837)   (1.67347, 2.0)
 (1.7551, -2.0)    (1.7551, -1.91837)       (1.7551, 1.91837)    (1.7551, 2.0)
 (1.83673, -2.0)   (1.83673, -1.91837)      (1.83673, 1.91837)   (1.83673, 2.0)
 (1.91837, -2.0)   (1.91837, -1.91837)      (1.91837, 1.91837)   (1.91837, 2.0)
 (2.0, -2.0)       (2.0, -1.91837)          (2.0, 1.91837)       (2.0, 2.0)

Although it doesn’t sound like quite what you’re after here, sometimes it can be useful to use CartesianIndices for things like this:

gridaxes = (x,y)
for ci in CartesianIndices(eachindex.(gridaxes))
    point = getindex.(gridaxes, Tuple(ci))
    # do stuff with point
end