3

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.

imlg
  • 131
  • 3
  • how do you know what the input arrays should be from `n=2` or are they also given? – ti7 Jun 10 '22 at 18:27
  • @ti7 the elements of the arrays are given and can be arbitrary, their size is n – imlg Jun 10 '22 at 18:34
  • 2
    It's considered bad form to change the question in a way that turns it into a completely different question after people have already answered. You got an answer to your original question, but edited the question in such a way that makes that answer seem totally incorrect. – Mark Jun 10 '22 at 18:45
  • Sorry, I realized that the example I gave was not representative of the general case – imlg Jun 10 '22 at 18:57
  • `np.array(np.meshgrid(arr1,arr1,arr2,arr2)).reshape(4,-1).T`. I don't know what *qi* is referring to in the question. – Michael Szczesny Jun 10 '22 at 19:21
  • BTW: `T[np.ix_([0,1],[0,1],[3,4],[3,4])].ravel()` extracts the same subarray without creating a dense indices array. – Michael Szczesny Jun 10 '22 at 19:35

1 Answers1

3
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)
AboAmmar
  • 5,439
  • 2
  • 13
  • 24