What is the equivalent of matlab's wkeep in Python?
<p>If I want to extract a vector of certain size from a matrix, how do I do it?</p>

<p>I'm looking for something that does exactly the same thing as <a href="http://in.mathworks.com/help/wavelet/ref/wkeep.html" rel="nofollow"><code>wkeep</code></a> in matlab</p>

<p>It turns out that a lot of the use-cases of <code>wkeep</code> can be written more idomatically:</p>

<pre><code>X[1:3,1:4]    # wkeep(X, [2, 3])
</code></pre>

<p>If you don't actually need it to be centered, you could use:</p>

<pre><code>X[:2, :4]     # wkeep(X, [2, 3], 'l')
X[-2:, -4:]   # wkeep(X, [2, 3], 'r')
</code></pre>

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

<pre><code>X[2:-2,2:-2]  # wkeep(X, size(X) - 2)
</code></pre>

<p><em>If you really want a direct translation</em> of <code>wkeep(X,L)</code>, here's what <code>wkeep</code> seems to do:</p>

<pre><code># 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 &lt;= L) &amp; (L &lt;= 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]
</code></pre>

<p>So for example:</p>

<pre><code>&gt;&gt;&gt; X = np.arange(20).reshape(4, 5)
&gt;&gt;&gt; centered_slice(X, [2, 3])
array([[ 6,  7,  8],
       [11, 12, 13]])
</code></pre>

python matlab numpy