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?