Reputation: 839
I'm new to python, and I know there must be a better way to do this, especially with numpy, and without appending to arrays. Is there a more concise way to do something like this in python?
def create_uniform_grid(low, high, bins=(10, 10)):
"""Define a uniformly-spaced grid that can be used to discretize a space.
Parameters
----------
low : array_like
Lower bounds for each dimension of the continuous space.
high : array_like
Upper bounds for each dimension of the continuous space.
bins : tuple
Number of bins along each corresponding dimension.
Returns
-------
grid : list of array_like
A list of arrays containing split points for each dimension.
"""
range1 = high[0] - low[0]
range2 = high[1] - low[1]
steps1 = range1 / bins[0]
steps2 = range2 / bins[1]
arr1 = []
arr2 = []
for i in range(0, bins[0] - 1):
if(i == 0):
arr1.append(low[0] + steps1)
arr2.append(low[1] + steps2)
else:
arr1.append(round((arr1[i - 1] + steps1), 1))
arr2.append(arr2[i - 1] + steps2)
return [arr1, arr2]
low = [-1.0, -5.0]
high = [1.0, 5.0]
create_uniform_grid(low, high)
# [[-0.8, -0.6, -0.4, -0.2, 0.0, 0.2, 0.4, 0.6, 0.8],
# [-4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0]]
Upvotes: 0
Views: 3074
Reputation: 53089
np.ogrid
is similar to your function. Differences: 1) It will keep the endpoints; 2) It will create a column and a row, so its output is 'broadcast ready':
>>> np.ogrid[-1:1:11j, -5:5:11j]
[array([[-1. ],
[-0.8],
[-0.6],
[-0.4],
[-0.2],
[ 0. ],
[ 0.2],
[ 0.4],
[ 0.6],
[ 0.8],
[ 1. ]]), array([[-5., -4., -3., -2., -1., 0., 1., 2., 3., 4., 5.]])]
Upvotes: 2
Reputation: 18341
Maybe the numpy.meshgrid
is what you want.
Here is an example to create the grid and do math on it:
#!/usr/bin/python3
# 2018.04.11 11:40:17 CST
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-5, 5, 0.1)
y = np.arange(-5, 5, 0.1)
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)
plt.imshow(z)
plt.show()
Refer:
Upvotes: 0