How could I pair up x and y generated by np.meshgrid using python?

Question:

I’m trying to generate a 2-dim coordinates matrix using python.

I’m using

x=np.linespace(min, max, step)
y=np.linespace(min, max, step)
X, Y = np.meshgrid(x, y)

to generate x and y coordinates, where X like:

[[0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]]

and Y like:

[[-2. -2. -2. -2. -2.]
 [-1. -1. -1. -1. -1.]
 [ 0.  0.  0.  0.  0.]
 [ 1.  1.  1.  1.  1.]
 [ 2.  2.  2.  2.  2.]
 [ 3.  3.  3.  3.  3.]
 [ 4.  4.  4.  4.  4.]
 [ 5.  5.  5.  5.  5.]]

I want to get:

[[[0, -2] [0, -1] [0, 0] [0, 1] [0, 2]]
 [[1, -2] [1, -1] [1, 0] [1, 1] [1, 2]]
 [[2, -2] [2, -1] [2, 0] [2, 1] [2, 2]]
 [[3, -2] [3, -1] [3, 0] [3, 1] [3, 2]]
 [[4, -2] [4, -1] [4, 0] [4, 1] [4, 2]]]

(or its horizontal mirror) How to do that?

Asked By: Winertoz Botawar

||

Answers:

You can implement something like this:

#!/usr/bin/env ipython
# ---------------------------
import numpy as np
x0,x1 = -2, 2
y0,y1 = 0,4
x=np.arange(x0,x1, 1)
y=np.arange(y0,y1, 1)
X, Y = np.meshgrid(x, y)
ny,nx = np.shape(X)
# -----------------------------------------------------------
ans = [[[X[jj,ii],Y[jj,ii]] for ii in range(nx) ] for jj in range(ny)]

I switched to np.arange instead of np.linspace.

Answered By: msi_gerva

You can use np.stack (a variant on np.concatenate) to join these 2 arrays – on any axis. np.stack((X,Y),axis=0) like np.array((X,Y)) will join them on a new leading dimension (2,8,6) shape. But apparently you think a new trailing dimension is best, so it needs axis=2.

Your X and Y were apparently generated with:

In [86]: X, Y = np.meshgrid(np.arange(0,6), np.arange(-2,6))

That’s two (8,6) arrays. The sample output is (5,5), but the layout looks like it’s part of (6,8,2) array, requiring transposes:

In [87]: np.stack((X.T,Y.T),axis=2)
Out[87]: 
array([[[ 0, -2],
        [ 0, -1],
        [ 0,  0],
        [ 0,  1],
        [ 0,  2],
        [ 0,  3],
        [ 0,  4],
        [ 0,  5]],

       [[ 1, -2],
        [ 1, -1],
        [ 1,  0],
        [ 1,  1],
        [ 1,  2],
        [ 1,  3],
        [ 1,  4],
        [ 1,  5]],
      ....

In fact you could just join them on the first axis, and transpose:

 np.array((X,Y)).T

Anyways, you can fiddle with the input arrays and the axis if you don’t like this shape.

Answered By: hpaulj
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.