0

I am working with a 5 dimensional array that is 5x5x5x5x5 in python.

How can I make a function that

  • will take an integer i (1<=i<=5) for which dimension to iterate through, and a list of the other 4 dimensions [a,b,c,d] to be locked in
  • return a 1-dimensional list of length 5

for example:

>>>bb = (5 dimensional array)

>>>rowExtract(3, [2,3,0,2], bb)

*[ bb[2][3][i][0][2] for i in range(5)] returns*

The 3 is for the 3rd dimension, and the 2,3,0,2 signifies the other dimensions

I could do it by hard coding 5 different scenarios, but is there an easier way?

3 Answers 3

1

Below is one way using loops.

def extract_row(row, arr, bb):
  N = len(arr) + 1

  pre_mat = bb
  for i in range(row):
    pre_mat = pre_mat[arr[i]]

  ans = [] 
  for i in range(N):
    mat = pre_mat[i]
    for j in range(row + 1, N):
      mat = mat[arr[j - 1]]

    ans.append(mat)

  return ans
Sign up to request clarification or add additional context in comments.

Comments

0

I think there is no other way. So something like this

def extractRow(row, arr, bb):
    if row == 0:
        return [bb[i][arr[0]][arr[1]][arr[2]][arr[3]] for i in range(5)]
    elif row == 1:
        return [bb[arr[0]][i][arr[1]][arr[2]][arr[3]] for i in range(5)]
    ...

1 Comment

Hmmm, I agree. I haven't seen a problem like this anywhere else on the internet. It seems like Python doesn't support such a specific issue. Thank you!
0

One possible solution uses an iterator to generate the sequence of indices. The "missing" dimension can be inserted into arr, and each time through the generator's loop it fills that index with the next value. Each time the generator yields, it produces a 5-element array containing the indices needed to extract the next value from bb. Then you can pick the element you want from bb.

def extract_row(row, bb, arr):
    retval = []
    for a0, a1, a2, a3, a4 in iter_indices(row, arr):
        retval.append(bb[a0][a1][a2][a3][a4])
    return retval

def iter_indices(row, arr):
    arr.insert(row, None)
    for i in range(5):
        arr[row] = i
        yield arr

# TEST CODE FOLLOWS
g = 0
def deepen(b, n):
    global g
    if n == 1:
        b.append(g)
        b.append(g+1)
        b.append(g+2)
        b.append(g+3)
        b.append(g+4)
        g += 5
        return b
    for m in range(5):
        b.append(deepen([], n-1))
    return b

a = []
deepen(a, 5)

# Run it using the test matrix a
print(extract_row(1, a, [1, 2, 3, 4]))
print(a[1][0][2][3][4], a[1][1][2][3][4], a[1][2][2][3][4], a[1][3][2][3][4], a[1][4][2][3][4])


Output is:
[694, 819, 944, 1069, 1194]
694 819 944 1069 1194

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.