HumanTorch
HumanTorch

Reputation: 359

Iterating over 3D numpy using one dimension as iterator remaining dimensions in the loop

Despite there being a number of similar questions related to iterating over a 3D array and after trying out some functions like nditer of numpy, I am still confused on how the following can be achieved:

I have a signal of dimensions (30, 11, 300) which is 30 trials of 11 signals containing 300 signal points.

Let this signal be denoted by the variable x_

I have another function which takes as input a (11, 300) matrix and plots it on 1 graph (11 signals containing 300 signal points plotted on a single graph). Let this function be sliding_window_plot.

Currently, I can get it to do this:

x_plot = x_[0,:,:]
for i in range(x_.shape[0]):
    sliding_window_plot(x_plot[:,:])

which plots THE SAME (first trial) 11 signals containing 300 points on 1 plot, 30 times. I want it to plot the i'th set of signals. Not the first (0th) trial of signals everytime. Any hints on how to attempt this?

Upvotes: 1

Views: 3194

Answers (3)

kmario23
kmario23

Reputation: 61315

In general for all nD-arrays where n>1, you can iterate over the very first dimension of the array as if you're iterating over any other iterable. For checking whether an array is an iterable, you can use np.iterable(arr). Here is an example:

In [9]: arr = np.arange(3 * 4 * 5).reshape(3, 4, 5) 

In [10]: arr.shape 
Out[10]: (3, 4, 5) 

In [11]: np.iterable(arr) 
Out[11]: True 

In [12]: for a in arr: 
    ...:     print(a.shape) 
    ...:                     
(4, 5)
(4, 5)
(4, 5)

So, in each iteration we get a matrix (of shape (4, 5)) as output. In total, 3 such outputs constitute the 3D array of shape (3, 4, 5)


If, for some reason, you want to iterate over other dimensions then you can use numpy.rollaxis to move the desired axis to the first position and then iterate over it as mentioned in iterating-over-arbitrary-dimension-of-numpy-array


NOTE: Having said that numpy.rollaxis is only maintained for backwards compatibility. So, it is recommended to use numpy.moveaxis instead for moving the desired axis to the first dimension.

Upvotes: 3

Pavan Yalamanchili
Pavan Yalamanchili

Reputation: 12099

You are hardcoding the 0th slice outside the for loop. You need to create x_plot to be inside the loop. In fact you can simplify your code by not using x_plot at all.

for i in rangge(x_.shape[0]): sliding_window_plot(x_[i])

Upvotes: 2

Mark
Mark

Reputation: 92440

You should be able to iterate over the first dimension with a for loop:

for s in x_:
    sliding_window_plot(s)

with each iteration s will be the next array of shape (11, 300).

Upvotes: 3

Related Questions