'How to create a uniform grid of n-dimensional vectors using numpy (in other words, uniformly fill a n-dimensional hypercube)?
In one dimension a "grid" would be an array of numbers between let's say 0 and 100. In two dimensions the grid would be an array of points like [0, 0] [0, 1] [0, 2]... [1,0], [1, 1] ... [99, 99]. In three dimensions and more dimensions it would look similar.
My current output is like that:
It doesn't create every combination of values for each value in the nth - 1 column.
The code I use is:
import numpy as np
class Cube:
side_len = 100
def __init__(self, n):
current_point = np.zeros(n)
self.arr = []
for i in range(n):
for j in range(Cube.side_len):
self.arr.append(current_point.copy())
current_point[i] += 1.0
self.arr.append([Cube.side_len for _ in range(n)])
self.arr = np.array(self.arr)
np.random.shuffle(self.arr)
if __name__ == '__main__':
cube(10)
I tried also with meshgrid but I could not understand the documentation. I wanted it to be a shallow list of points but I get X, Y and I don't get what I am supposed to do with that?
Solution 1:[1]
Here's the way you do it. Meshgrid with 3 dimensions returns a list of three things, which are the values for the 3 axes to get a uniform spread of points. You can then use vstack to stack those together, and transpose to get a list of 3D coordinates:
>>> import numpy as np
>>> a = np.linspace(0,100,101)
>>> x = np.meshgrid( a, a, a )
>>> y = np.vstack(list(map(np.ravel,x))).T
>>> y
array([[ 0., 0., 0.],
[ 0., 0., 1.],
[ 0., 0., 2.],
...,
[100., 100., 98.],
[100., 100., 99.],
[100., 100., 100.]])
>>>
Credit to this post: How to convert the output of meshgrid to the corresponding array of points?
Remember that the grid is the size of one axis cubed, so these very quickly get large.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

