3

What could be an efficient way of creating numpy array containing the coordinates of vertices of the N-dimensional cube centered at origin of coordinates, given the dimension N.

For example, for N=1 it should return np.array([[1],[-1]])

For N=2 it should return np.array([[1,1],[1,-1],[-1,1],[-1,-1]])

For N=3: np.array([[1,1,1],[1,1,-1],[1,-1,1],[1,-1,-1],[-1,1,1],[-1,1,-1],[-1,-1,1],[-1,-1,-1]])

3 Answers 3

5

You can use product from itertools

from itertools import product

def vertices(N): 
    return list(product((1, -1), repeat=N))

print(vertices(1))
# [(1,), (-1,)]

print(vertices(2))
# [(1, 1), (1, -1), (-1, 1), (-1, -1)]

print(vertices(3))
# [(1, 1, 1), (1, 1, -1), (1, -1, 1), (1, -1, -1), (-1, 1, 1), (-1, 1, -1), (-1, -1, 1), (-1, -1, -1)]
Sign up to request clarification or add additional context in comments.

Comments

2

Here's another method: 2*((np.arange(2**N)[:,None] & (1 << np.arange(N))) > 0) - 1

In [25]: N = 1

In [26]: 2*((np.arange(2**N)[:,None] & (1 << np.arange(N))) > 0) - 1
Out[26]: 
array([[-1],
       [ 1]])

In [27]: N = 2

In [28]: 2*((np.arange(2**N)[:,None] & (1 << np.arange(N))) > 0) - 1
Out[28]: 
array([[-1, -1],
       [ 1, -1],
       [-1,  1],
       [ 1,  1]])

In [29]: N = 3

In [30]: 2*((np.arange(2**N)[:,None] & (1 << np.arange(N))) > 0) - 1
Out[30]: 
array([[-1, -1, -1],
       [ 1, -1, -1],
       [-1,  1, -1],
       [ 1,  1, -1],
       [-1, -1,  1],
       [ 1, -1,  1],
       [-1,  1,  1],
       [ 1,  1,  1]])

What it does:

  • Create an array of integers from 0 to 2**N-1.
  • Convert the integers to binary (e.g. 3 becomes [1, 1, 0]).
  • Multiply the binary array by 2 and subtract 1 to convert from 0 and 1 to -1 and 1.

Numpy broadcasting is used to vectorize the operations.

1 Comment

@kevinkayaks I added a brief explanation to the answer.
2

Here is a pure numpy implementation involving meshgrid and stack. It's a little contrived-- would welcome input to make it better.

pts = np.stack(([-1,1],)*N,0)
vertices = (np.array(np.meshgrid(*pts)).T).reshape(2**N,N)
vertices

N=3 returns

array([[-1, -1, -1],
       [-1,  1, -1],
       [ 1, -1, -1],
       [ 1,  1, -1],
       [-1, -1,  1],
       [-1,  1,  1],
       [ 1, -1,  1],
       [ 1,  1,  1]])

N=1 returns

array([[-1],
       [ 1]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.