Metal Metal - 8 months ago 72
Python Question

What is the equivalent of matlab's wkeep in Python?

If I want to extract a vector of certain size from a matrix, how do I do it?

I'm looking for something that does exactly the same thing as

in matlab


It turns out that a lot of the use-cases of wkeep can be written more idomatically:

X[1:3,1:4]    # wkeep(X, [2, 3])

If you don't actually need it to be centered, you could use:

X[:2, :4]     # wkeep(X, [2, 3], 'l')
X[-2:, -4:]   # wkeep(X, [2, 3], 'r')

Or if the real reason you're using wkeep is to trim off a border:

X[2:-2,2:-2]  # wkeep(X, size(X) - 2)

If you really want a direct translation of wkeep(X,L), here's what wkeep seems to do:

# Matlab has this terrible habit of implementing general functions
# in specific packages, and naming after only their specific use case.
# let's pick a name that actually tells us what this does
def centered_slice(X, L):
    L = np.asarray(L)
    shape = np.array(X.shape)

    # verify assumptions
    assert L.shape == (X.ndim,)
    assert ((0 <= L) & (L <= shape)).all()

    # calculate start and end indices for each axis
    starts = (shape - L) // 2
    stops = starts + L

    # convert to a single index
    idx = tuple(np.s_[a:b] for a, b in zip(starts, stops))
    return X[idx]

So for example:

>>> X = np.arange(20).reshape(4, 5)
>>> centered_slice(X, [2, 3])
array([[ 6,  7,  8],
       [11, 12, 13]])