In my application I have a matrix of values and its coordinates (lon, lat) obtained from a meshgrid command.
I want to extract a particular sub-region of this matrix based on longitude and latitude limits. I've tried this solution but it doesn't work. I need as output three matrices one for the data and the other two for the grid.
Lons, Lats = meshgrid(X, Y)
indexes = np.where((Lons < MLon) & (Lons > mLon) & (Lats < MLat) & (Lats > mLat))
newLons = Lons[indexes]
newLats = Lats[indexes]
newData = Data[indexes]
The new values obtained are one dimensional arrays and not matrices.
How can I fix this?
There is no guarantee from np.where
's viewpoint that you will extract values that make out a contiguous rectangular submatrix, so it returns them flat. You could reshape them, but for that you need to figure out what their shape is. A better and more general solution would be to find the bounding box and then extract that:
Xspan = np.where((X < MLon) & (X > mLon))[0][[0, -1]]
Yspan = np.where((Y < MLat) & (Y > mLat))[0][[0, -1]]
# Create a selection
sel = [slice(Xspan[0], Xspan[1] + 1), slice(Yspan[0], Yspan[1] + 1)]
# Extract
newLons = Lons[sel] # == Lons[Xspan[0]:Xspan[1]+1, Yspan[0]:Yspan[1]+1]
newLats = Lats[sel]
newData = Data[sel]