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.

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Looks good to me - just watch out for the indexing='ij' vs indexing='xy' thing when generalising to higher dims.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.