3

I am looking to put the x and y values of the coordinate grid into their own separate arrays in order to perform functions such as Pythagoras etc. Here's my code below.

x1d = np.linspace(-xlen,xlen,res)
y1d = np.linspace(-ylen,ylen,res)
from itertools import product
coordinates = list(product(x1d, y1d))
xcoord = coordinates[:][:][0]

print np.shape(coordinates), np.shape(xcoord), coordinates

I get that the below code will give me

coordinates = [[x1,y1],[x2,y2],...,[xn,yn]].

How would one go about extracting the following arrays?

xcoord = [x1,x2,...,xn]
ycoord = [x1,x2,...,xn]

Is this the right solution for generating a 2D grid of points where I can perform functions upon each individual x,y point, assigning a resultant value to that point?

Thanks!

smashbro
  • 1,094
  • 1
  • 9
  • 19
  • The code you have will not do what you think it will. Take a look at the following: http://stackoverflow.com/questions/11144513/numpy-cartesian-product-of-x-and-y-array-points-into-single-array-of-2d-points – user2357112 Nov 28 '13 at 22:37

2 Answers2

2

You could also use itertools to get your x and y values:

import itertools
x,y=itertools.izip(*coordinates)

# x=(x1,x2,...,xn)
# y=(y1,y2,...,yn)

In regards to the grid, have a look at numpy's meshgrid which could be useful for you. You can use it like so (taken from the example on the linked website):

x=np.arange(-5,5,.1)

y=np.arange(-5,5,.1)

xx,yy=meshgrid(x,y,sparse=True)

xx,yy=np.meshgrid(x,y,sparse=True)

z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)

h = plt.contourf(x,y,z)

Numpy's meshgrid

pandita
  • 4,739
  • 6
  • 29
  • 51
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – Raptor Nov 28 '13 at 07:50
  • @Shivan Why not? If I do `x,y=itertools.izip(zip(range(10),range(10,20))` i get `x=(0,1,2,...)` and `y=(10,11,...)` which I think is what has been asked... – pandita Nov 28 '13 at 07:54
  • 1
    @Shivan I added some words around it... I hope this is clearer now – pandita Nov 28 '13 at 07:59
0

Treating it as a normal list, you can use a list comprehension:

xcord, ycord = [e[0] for e in coordinates], [e[1] for e in coordinates]

Hope this helps!

aIKid
  • 26,968
  • 4
  • 39
  • 65