0

I have seen similar questions but none that need the format of the output array of shape (numpoints, dim)

Here is a simple example of what I have for dim=2

import numpy as np

bounds = [0.5, 0.5]
n = [10,10]
dim = 2
x = np.linspace(-bounds[0], bounds[0], n[0])
y = np.linspace(-bounds[1], bounds[1], n[1])
X, Y = np.meshgrid(x, y)

s = X.shape
data = np.zeros((n[0]*n[1],dim)) 

# convert mesh into point vector for which the model can be evaluated
c = 0
for i in range(s[0]):
    for j in range(s[1]):
        data[c,0] = X[i,j]
        data[c,1] = Y[i,j]
        c = c+1;
plt.scatter(data[:,0], data[:,1])

enter image description here

Is there a faster/better way of doing this so that the data are arranged in this way? I want a general method that could work for any dim.

Edit: Suggested answer does not work.

  • Does this answer your question? [How to convert the output of meshgrid to the corresponding array of points?](https://stackoverflow.com/questions/12864445/how-to-convert-the-output-of-meshgrid-to-the-corresponding-array-of-points) – Michael Szczesny Aug 11 '22 at 15:00
  • @MichaelSzczesny when I use the suggested 'meshgrid2' function I get the error 'map' object not subscriptable. So yes, the question is similar – Kyriacos Xanthos Aug 11 '22 at 15:16

2 Answers2

1

Yeah, that can be vectorized with

axis_coords = np.meshgrid(x, y, indexing='xy')
data = np.hstack([c.reshape(-1, 1) for c in axis_coords])

c.reshape(-1, 1) just reshapes c from (HxW to (H*W)x1) so that it can be stacked horizontally.

Note - if you're looking to generalize to more dims you probably want to switch to indexing='ij' so it's arranged by (row, column, dim2, dim3, ...) rather than (column, row, dim2, dim3, ...) since in numpy rows are considered the 0'th dimension and columns the 1st.

Peter
  • 12,274
  • 9
  • 71
  • 86
  • Thanks for your answer, but I think this is not general enough for any dimension. I posted my answer, take a look at it and let me know. – Kyriacos Xanthos Aug 12 '22 at 07:11
  • Looks good to me - just watch out for the `indexing='ij'` vs `indexing='xy'` thing when generalising to higher dims. – Peter Aug 12 '22 at 13:19
1

I managed to solve my problem with this function that is general enough for any dim:

def get_grid_of_points(n, *args):
    ls = [np.linspace(-i,i,n) for i in args]
    mesh_ls = np.meshgrid(*ls)
    all_mesh = [np.reshape(x, [-1]) for x in mesh_ls]
    grid_points = np.stack(all_mesh, axis=1)
    return grid_points

get_grid_of_points(10, 0.5, 0.5)

enter image description here