Taking subarrays from numpy array with given stride
<p>Lets say I have a Python Numpy array array a.</p>

<pre><code>numpy.array([1,2,3,4,5,6,7,8,9,10,11].)
</code></pre>

<p>I want to create a matrix of sub sequences from this array of length 5 with stride 3. The results matrix hence will look as follows:</p>

<pre><code>numpy.array([[1,2,3,4,5],[4,5,6,7,8],[7,8,9,10,11]])
</code></pre>

<p>One possible way of implementing this would be using a for-loop.</p>

<pre><code>result_matrix = np.zeros((3, 5))
for i in range(0, len(a), 3):
  result_matrix[i] = a[i:i+5]
</code></pre>

<p>Is there a cleaner way to implement this is Numpy?</p>

<p><strong>Approach #1 :</strong>  Using <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> -</p>

<pre><code>nrows = ((a.size-L)//S)+1
out = a[S*np.arange(nrows)[:,None] + np.arange(L)]
</code></pre>

<p><strong>Approach #2 :</strong> Using more efficient <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.strides.html" rel="nofollow"><code>NumPy strides</code></a> -</p>

<pre><code>n = a.strides[0]
out = np.lib.stride_tricks.as_strided(a, shape=(nrows,L), strides=(S*n,n))
</code></pre>

<p>Sample run -</p>

<pre><code>In [183]: a
Out[183]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

In [184]: L = 5 # length

In [185]: S = 3 # stride

In [186]: nrows = ((a.size-L)//S)+1

In [187]: a[S*np.arange(nrows)[:,None] + np.arange(L)]
Out[187]: 
array([[ 1,  2,  3,  4,  5],
       [ 4,  5,  6,  7,  8],
       [ 7,  8,  9, 10, 11]])

In [188]: n = a.strides[0]

In [189]: np.lib.stride_tricks.as_strided(a, shape=(nrows,L), strides=(S*n,n))
Out[189]: 
array([[ 1,  2,  3,  4,  5],
       [ 4,  5,  6,  7,  8],
       [ 7,  8,  9, 10, 11]])
</code></pre>

python numpy vectorization