Reputation: 1573
I would like to create a n-dimensional matrix containing all possible combinations with array values between -1 and +1.
So for n = 2 this would look like to following:
[[-1,-1], [-1,0], [-1,+1], [0,-1], [0,0], [0,+1], [1,-1], [1,0], [1,1]]
The matrix itself will be used to calculate surrounding points of an object.
I already wrote a quite simple solution using multiple for loops, but I would like the solution to be independent from the dimension. I hope someone can help.
Upvotes: 0
Views: 461
Reputation: 41872
This sounds like an opportunity to play with functions in the itertools module that I normally don't have a need for:
from itertools import product, repeat
def n_dimensional_matrix(n, start=-1, stop=1):
return product(*repeat(range(start, stop+1), n))
Now try the 2 dimensional example:
>>> matrix = n_dimensional_matrix(2)
>>>
>>> print(list(matrix))
[(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 0), (0, 1), (1, -1), (1, 0), (1, 1)]
Heman Gandhi has clarified what the output for greater dimensions should be (thank you):
>>> list(n_dimensional_matrix(3))
[(-1, -1, -1), (-1, -1, 0), (-1, -1, 1), (-1, 0, -1), (-1, 0, 0), (-1, 0, 1), (-1, 1, -1), (-1, 1, 0), (-1, 1, 1), (0, -1, -1), (0, -1, 0), (0, -1, 1), (0, 0, -1), (0, 0, 0), (0, 0, 1), (0, 1, -1), (0, 1, 0), (0, 1, 1), (1, -1, -1), (1, -1, 0), (1, -1, 1), (1, 0, -1), (1, 0, 0), (1, 0, 1), (1, 1, -1), (1, 1, 0), (1, 1, 1)]
Upvotes: 0
Reputation: 1371
def n_dims(dims, start, stop):
if dims == 1:
return list(map(lambda x: [x], range(start, stop)))
else:
p = n_dims(dims - 1, start, stop)
a = []
for i in range(start, stop):
a += [j + [i] for j in p]
return a
This appeared to work in python 3. Hope it helps.
Upvotes: 1