1

I have a 3D matrix such as:

array([[[3., 0., 0.],
        [0., 0., 0.],
        [0., 0., 0.]],
       [[0., 0., 0.],
        [2., 0., 0.],
        [0., 0., 0.]],
       [[0., 0., 0.],
        [12., 0., 0.],
        [0., 0., 0.]]])

I want to slice this in [: , 0, :], [-1,: :].. and all 6 directions in the order with a for loop. So for each dimension, slicing from the first (0) and last (-1).

What is the proper way of applying the for loop?

Lets assume the name of the array is A:

A[0, :, :]
A[:, :, 0]
A[:, 0, :]
A[-1, :, :]
A[:, -1, :]
A[:, :, -1]

I want to have these 6 submatrices (lets say in a list) in one loop.

4
  • what do you mean by "all 6 directions" and "in the order"? It might help if you give an example of the output you expect. Commented Oct 11, 2019 at 16:17
  • 1
    You almost never need loops with NumPy. The best answer is very unlikely to involve loops. It would help if you show what output you expect from your input? Commented Oct 11, 2019 at 16:27
  • 2
    This is a (3,3,3) shaped array. You need to be more explicit about what you want to do - examples of the resulting slices. Often the action is clearer if you use an array like np.arange(24).reshape(2,3,4) - distinct dimensions, and values. Commented Oct 11, 2019 at 19:06
  • 1
    edited the questions to make it a bit clearer. Reshaping is not an option. Commented Oct 11, 2019 at 19:30

1 Answer 1

2

It's not clear at all why you want to do this, but you can dynamically snatch subarrays using take:

import numpy as np
arr = np.arange(2*3*4).reshape(2, 3, 4)  # dummy input

arrays = [arr.take(index, axis) for axis in range(arr.ndim) for index in [0,-1]]

This list of arrays will contain arr[0,:,:], arr[-1,:,:], arr[:,0,:], arr[:,-1,:] etc. in this order. Here's proof for a single element in the list of arrays:

>>> np.array_equal(arr[:,-1,:], arr.take(-1, 1))
True

Your question wasn't too specific about the order, but the above can easily be generalized for an arbitrary ordering of your slicing requirements:

indices = [0, 0, 0, -1, -1, -1]
axes = [0, 2, 1, 0, 1, 2]
arrays = [arr.take(index, axis) for index,axis in zip(indices, axes)]

This matches the order of the subarrays as specified in your question.

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

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.