0

I have an array with dimensions (Nt, Nx0, Ny0). For each index in axis 0, I want to randomly select a 'rectangle' in axis 1 and 2. The rectangle has a fixed size Nx1 by Nx2 with Nx1 < Nx0 and Ny1 < Ny0.

This code does what I want to do:

import numpy as np

for i in range(Nt):
    x0ind = round(0.5*(Nx0-Nx1))+np.random.randint(-max_x, max_x)
    x1ind = x0ind+Nx1

    y0ind = round(0.5*(Ny0-Ny1))+np.random.randint(-max_y, max_y)
    y1ind = y0ind+Ny1

    ar1[i,:,:] = ar0[i,x0ind:x1ind,y0ind:y1ind]

I feel it should be possible to do this using numpy indexing, for example:

import numpy as np

Nt = 100
Nx0 = 70
Ny0 = 70

Nx1 = 50
Ny1 = 50

max_x = 5
max_y = 5

ar0 = np.random.rand(Nt, Nx0, Ny0)

x_ind = np.random.randint(-max_x, max_x)
y_ind = np.random.randint(-max_y, max_y)

ar1 = ar0[:, x_ind:x_ind+Nx1, y_ind:y_ind+Ny1]

However, this does not work. Should it be possible to do this without a for loop?

2
  • When you want to index several blocks like this you either have to join them after indexing as you do in the first case, or build an equivalent array of indices which you then apply. It should be easy to find 1d examples of this, e.g. [x[i:j] for i,j in zip(....)]. The same issues apply to your 3d case. Keep in mind that while you are indexing with slices, ar1 will be copy, not a view. Commented Mar 7, 2018 at 18:07
  • An earlier 1d example, Index multiple, non-adjacent ranges in numpy; or a more complex case, Select from multiple slices in Numpy Commented Mar 7, 2018 at 18:23

0

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.