I want to iterate over some inner dimensions of an array without knowing in advance how many dimensions to iterate over. Furthermore I only know that the last two dimensions should not be iterated over.
For example assume the array has dimension 5 and shape (i,j,k,l,m)
and I want to iterate over the second and third dimension. In each step of the iteration I expect an array of shape (i,l,m)
.
Example 1: Iterate over second dimension of x
with x.ndim=4
, x.shape=(I,J,K,L)
.
Expected: x[:,j,:,:]
for j=0,...,J-1
Example 2: Iterate over second and third dimension of x
with x.ndim=5
, x.shape=(I,J,K,L,M)
Expected: x[:,j,k,:,:]
for j=0,...,J-1
, k=0,...,K-1
Example 3: Iterate over second, third and fourth dimension of x
with x.ndim=6
, x.shape=(I,J,K,L,M,N)
Expected: x[:,j,k,l,:,:]
for j=0,...,J-1
, k=0,...,K-1
and l=0,...,L-1
Assume the array has dimension 5 and shape (i,j,k,l,m)
.
If I know which dimension to iterate over, for example the second and third axis, this is possible with a nested for-loop
:
for j in range(x.shape[1]):
for k in range(x.shape[2]):
x[...,j,k,:,:]
However since I do not know in advance how many dimensions I want to iterate over for-loops are not an option. I found a way to generate the indices based on the shapes of the dimensions I want to iterate over.
for b in product(*map(range, x.shape[2:4])):
print(b)
>>> (0, 0)
>>> (0, 1)
>>> ...
>>> (0, k)
>>> ...
>>> (j, k)
This yields the indices for arbitrary inner dimension which is what I want. However I'm not aware of a way to use this tuple directly to slice into an an array. Therefore I first need to assign these entries to variables and then use these variables for slicing.
for b in product(*map(range,x.shape[2:4])):
j,k=b
x[...,j,k,:,:]
But this approach again only works if I know in advance how many dimensions to iterate over.