Generate quadruples of pairs

Viewed 49

I'm having trouble getting the following quadruples in Python. Let n be an integer, for example n=2, then the algorithm should do the following:

Input: two 2x1 arrays of integers, arr1 = [0,1] and arr2 = [3,4]

Ouput: 2x4 array

quads = [[0,0,3,3],
         [0,0,3,4],
         [0,0,4,3],
         [0,0,4,4],
         [0,1,3,3],
         [0,1,3,4],
         [0,1,4,3],
         [0,1,4,4],
         [1,0,3,3],
         ...
        ]

and so on, writing again the second row but with 1 in the first column instead of 0.

My intuition is that this is possible by using tile and repeat, something like

import numpy as np
n = 3
arr = np.arange(n)

ix =         np.repeat(arr,n**4)
iy = np.tile(np.repeat(arr,n**2),n**2)
ik = np.tile(np.repeat(arr,n**1),n**3)
il = np.tile(arr                ,n**4)

quad = np.column_stack((ix,iy,ik,il))

but I can't make this work. Any ideas on more efficient numpy functions that directly achieve this (is this possible using meshgrid?) would be helpful.

Why I need this: qi will finally be used as index to extract the subtensor T[qi] where T is a tensor with 4 dimensions.

1 Answers
from itertools import product
arr0 = [3,4]
quad = product(arr0, repeat=4)

print(*quad)
(3, 3, 3, 3) (3, 3, 3, 4) (3, 3, 4, 3) (3, 3, 4, 4) (3, 4, 3, 3) (3, 4, 3, 4) (3, 4, 4, 3) (3, 4, 4, 4) (4, 3, 3, 3) (4, 3, 3, 4) (4, 3, 4, 3) (4, 3, 4, 4) (4, 4, 3, 3) (4, 4, 3, 4) (4, 4, 4, 3) (4, 4, 4, 4)

Edit: answer to your edited question:

arr0 = [0,1]
arr1 = [3,4]
quad = product(arr0, arr0, arr1, arr1)
Related