Lets say I have a Python Numpy array array a.
numpy.array([1,2,3,4,5,6,7,8,9,10,11].)
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:
numpy.array([[1,2,3,4,5],[4,5,6,7,8],[7,8,9,10,11]])
One possible way of implementing this would be using a for-loop.
result_matrix = np.zeros((3, 5))
for i in range(0, len(a), 3):
result_matrix[i] = a[i:i+5]
Is there a cleaner way to implement this is Numpy?
Approach #1 : Using
broadcasting
-Approach #2 : Using more efficient
NumPy strides
-Sample run -