2

Let's say I have a 10 x 20 matrix of values (so 200 data points)

values = np.random.rand(10,20)

with a known regular spacing between coordinates so that the x and y coordinates are defined by

coord_x = np.arange(0,5,0.5)  --> gives [0.0,0.5,1.0,1.5...4.5]
coord_y = np.arange(0,5,0.25) --> gives [0.0,0.25,0.50,0.75...4.5]

I'd like to get an array representing each coordinates points so that the shape of the array is (200,2), 200 being the total number of points and the extra dimension simply representing x and y such as

coord[0][0]=0.0, coord[0][1]=0.0
coord[1][0]=0.0, coord[1][1]=0.25
coord[2][0]=0.0, coord[2][1]=0.50
...
coord[19][0]=0.0, coord[19][1]=5.0
coord[20][0]=0.5, coord[20][1]=0.0
coord[21][0]=0.5, coord[21][1]=0.25
coord[22][0]=0.5, coord[22][1]=0.50
...
coord[199][0]=4.5, coord[199][1]=4.5

That would a fairly easy thing to do with a double for loop, but I wonder if there is more elegant solution using built-in numpy (or else) functions.

?

2 Answers 2

2

I think meshgrid may be what you're looking for.

Here's an example, with smaller number of datapoints:

>>> from numpy import fliplr, dstack, meshgrid, linspace
>>> x, y, nx, ny = 4.5, 4.5, 3, 10
>>> Xs = linspace(0, x, nx)
>>> Ys = linspace(0, y, ny)
>>> fliplr(dstack(meshgrid(Xs, Ys)).reshape(nx * ny, 2))

array([[ 0.  ,  0.  ],
       [ 0.  ,  2.25],
       [ 0.  ,  4.5 ],
       [ 0.5 ,  0.  ],
       [ 0.5 ,  2.25],
       [ 0.5 ,  4.5 ],
       [ 1.  ,  0.  ],
       [ 1.  ,  2.25],
       [ 1.  ,  4.5 ],
       [ 1.5 ,  0.  ],
       [ 1.5 ,  2.25],
       [ 1.5 ,  4.5 ],
       [ 2.  ,  0.  ],
       [ 2.  ,  2.25],
       [ 2.  ,  4.5 ],
       [ 2.5 ,  0.  ],
       [ 2.5 ,  2.25],
       [ 2.5 ,  4.5 ],
       [ 3.  ,  0.  ],
       [ 3.  ,  2.25],
       [ 3.  ,  4.5 ],
       [ 3.5 ,  0.  ],
       [ 3.5 ,  2.25],
       [ 3.5 ,  4.5 ],
       [ 4.  ,  0.  ],
       [ 4.  ,  2.25],
       [ 4.  ,  4.5 ],
       [ 4.5 ,  0.  ],
       [ 4.5 ,  2.25],
       [ 4.5 ,  4.5 ]])
Sign up to request clarification or add additional context in comments.

Comments

1

I think you meant coord_y = np.arange(0,5,0.25) in your question. You can do

from numpy import meshgrid,column_stack
x,y=meshgrid(coord_x,coord_y)
coord = column_stack((x.T.flatten(),y.T.flatten()))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.