Home >Backend Development >Python Tutorial >How to Efficiently Extract Subarrays with Strides in NumPy?

How to Efficiently Extract Subarrays with Strides in NumPy?

Barbara Streisand
Barbara StreisandOriginal
2024-12-03 18:05:16271browse

How to Efficiently Extract Subarrays with Strides in NumPy?

Subarray Extraction with Strides in Numpy Arrays

Consider a Python Numpy array a:

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

We aim to extract subarrays of length 5 with a stride of 3. This results in a matrix with the following content:

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

Cleaner Implementation

While a for-loop approach is viable, Numpy provides more efficient methods:

Approach 1: Broadcasting

This approach takes advantage of broadcasting:

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

Approach 2: Strides Optimization

This method utilizes Numpy's efficient strides:

def strided_app(a, L, S ):  # Window len = L, Stride len/stepsize = 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))

Usage Example:

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

broadcasting_app(a, L = 5, S = 3)
# [[ 1  2  3  4  5]
#  [ 4  5  6  7  8]
#  [ 7  8  9 10 11]]

strided_app(a, L = 5, S = 3)
# [[ 1  2  3  4  5]
#  [ 4  5  6  7  8]
#  [ 7  8  9 10 11]]

These approaches offer more efficient and optimized solutions for extracting subarrays with strides in Numpy arrays.

The above is the detailed content of How to Efficiently Extract Subarrays with Strides in NumPy?. 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