selecting all 2-d slices out of n-dimensional array
by Moroney, Catherine M (398E)
I have an n-dimensional array (say (4,4,2,2)) and I wish to automatically extract all the (4,4) slices in it.
a = numpy.arange(0, 64).reshape(4,4,2,2)
slice1 = a[..., 0, 0]
slice2 = a[..., 0, 1]
slice3 = a[..., 1, 0]
slice4 = a[..., 1,1]
Simple enough example but in my case array “a” will have unknown rank and size. All I know is that it will have more than 2 dimensions, but I don’t know ahead of time how many dimensions or what the size of those dimensions are.
What is the best way of tackling this problem without writing a whole bunch of if-then cases depending on what the rank and shape of a is? Is there a one-size-fits-all solution?
I’m using python 2.7 and numpy 1.8.2
Thanks for any advice,