Skip to content
Advertisement

Iterate over inner axes of an array

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:

JavaScript

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.

JavaScript

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.

JavaScript

But this approach again only works if I know in advance how many dimensions to iterate over.

Advertisement

Answer

With the caveat that I don’t fully understand how you want to use this, I reckon the following should do what you are asking for:

JavaScript

Example:

JavaScript

Notes:

  1. The axes to iterate over may be in any order, e.g.:

    JavaScript
  2. The sub arrays can be used as L-values (modified in place), with the original array modified accordingly. This is due to np.moveaxis() returning a view of the original array (numpy never ceases to amaze me):

    JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement