简体   繁体   中英

Creating N-Dimensional “Permutation” Matrix

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.

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.

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM