Home >Backend Development >Python Tutorial >How to Efficiently Create Subarrays from a NumPy Array with a Stride?

How to Efficiently Create Subarrays from a NumPy Array with a Stride?

Susan Sarandon
Susan SarandonOriginal
2024-12-02 18:18:11991browse

How to Efficiently Create Subarrays from a NumPy Array with a Stride?

Taking Subarrays from Numpy Array with Stride/Stepsize

In this context, we discuss an efficient approach in Python NumPy to create subarrays from a given array with a specific stride.

To achieve this, we explore two methods:

1. Broadcasting Approach:

def broadcasting_app(a, L, S):
    nrows = ((a.size - L) // S) + 1
    return a[S * np.arange(nrows)[:, None] + np.arange(L)]

In this method, broadcasting is used to create a matrix of strides.

2. Efficient NumPy Strides Approach:

def strided_app(a, L, S):
    nrows = ((a.size - L) // S) + 1
    n = a.strides[0]
    return np.lib.stride_tricks.as_strided(a, shape=(nrows, L), strides=(S * n, n))

This method utilizes NumPy's efficient strides to create the subarray matrix.

Example:

Consider an array a:

a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])

To create subarrays of length 5 with a stride of 3, we can use either of the methods:

subarrays_broadcasting = broadcasting_app(a, L=5, S=3)
subarrays_strides = strided_app(a, L=5, S=3)

Both approaches will produce the following result:

[[ 1  2  3  4  5]
 [ 4  5  6  7  8]
 [ 7  8  9 10 11]]

The above is the detailed content of How to Efficiently Create Subarrays from a NumPy Array with a Stride?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn