Return coordinate matrices from coordinate vectors.
Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, given one-dimensional coordinate arrays x1, x2,..., xn.
import numpy as np
x = np.arange(-5, 5.1, 0.5)
y = np.arange(-5, 5.1, 0.5)
X,Y = np.meshgrid(x,y)
Not sure if I understand the question - to make a list of 2-element NumPy arrays, this works:
import numpy as np
x = np.arange(-5, 5.1, 0.5)
X, Y = np.meshgrid(x, x)
Liszt = [np.array(thing) for thing in zip(X.flatten(), Y.flatten())] # for python 2.7
zip gives you a list of tuples, and the list comprehension does the rest.
You can use np.mgrid for this, it's often more convenient than np.meshgrid because it creates the arrays in one step:
import numpy as np
X,Y = np.mgrid[-5:5.1:0.5, -5:5.1:0.5]
For linspace-like functionality, replace the step (i.e. 0.5) with a complex number whose magnitude specifies the number of points you want in the series. Using this syntax, the same arrays as above are specified as:
X, Y = np.mgrid[-5:5:21j, -5:5:21j]
You can then create your pairs as:
xy = np.vstack((X.flatten(), Y.flatten())).T
As @ali_m suggested, this can all be done in one line:
If you just want to iterate through pairs (and not do calculations on the whole set of points at once), you may be best served by itertools.product to iterate through all possible pairs:
import itertools
for (xi, yi) in itertools.product(x, y):
print(xi, yi)
This avoids generating large matrices via meshgrid.
It is not super fast solution, but works for any dimension
import numpy as np
def linspace_md(v_min,v_max,dim,num):
output = np.empty( (num**dim,dim) )
values = np.linspace(v_min,v_max,num)
for i in range(output.shape[0]):
for d in range(dim):
output[i][d] = values[( i//(dim**d) )%num]
return output
You can take advantage of Numpy's broadcasting rules to create grids simply. For example here is what I do when I want to do the equivalent of np.reshape (which is another fine option) on a linear array counting from 1 to 24:
Note np.newaxis is an alias for None and is used to expand the dimension of an Numpy array. Many prefer np.newaxis instead of None as I have used for its readability.
Here I used a sum to combine the grid, so it will be the row plus the first column element to make the first row in the result, then the same row plus the second column element to make the second row in the result etc. Other arithmetic operations can be used for any grid desired when the contents are based on two arrays like this.
As described, the above is identical to the result returned by reshape as given below, but the broadcasting option provides greater flexibility for other options so is worth noting.