Home > OS >  Elegant way to create a discrete coordinate system array in numpy
Elegant way to create a discrete coordinate system array in numpy

Time:03-06

I want to define an array which contains all combinations of values

[0, 0], [0, 1], [0, 2], ..., [0,N],

[1, 0], [1, 1], [1, 2], ..., [1, N],

...

[N, 0], [N, 1], [N,2], ..., [N,N].

Obviously, one could do something like this:

N = 10
array = np.array([[0,0]])
for i in range(N):
    for j in range(N):
        array = np.append(array, [[i,j]], axis=0)
print(array)

However, I find this "ugly". Is there a clean way to generate such an array?

CodePudding user response:

You can use np.indices, if you prefer:

data=np.indices((512,512)).swapaxes(0,2).swapaxes(0,1)
data.shape
# output: (512, 512, 2)

data[5,0]
# output: array([5, 0])
data[5,25]
#output: array([5, 25])

CodePudding user response:

Here are a few ideas you can probably use as well.

Using combinations from itertools:

from itertools import combinations
someList = [i for i in combinations(range(N), 2)]

Using product is a nice way to reduce nested for loops and condense down into list comprehensions:

someList = [[i,j] for i,j in product(range(N), range(N))]
  • Related