Home >Backend Development >Python Tutorial >How to Efficiently Create NumPy Subarrays with Custom Strides?

How to Efficiently Create NumPy Subarrays with Custom Strides?

Barbara Streisand
Barbara StreisandOriginal
2024-11-30 22:18:12305browse

How to Efficiently Create NumPy Subarrays with Custom Strides?

Numpy Subarrays with Custom Stride

Creating subarrays from a NumPy array with a given stride can be achieved in several ways. Here are two efficient approaches:

Broadcasting Approach:

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)]

Strided Approach:

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))

Example:

Consider the NumPy array a:

a = numpy.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 approach:

broadcasting_result = broadcasting_app(a, L=5, S=3)

strided_result = strided_app(a, L=5, S=3)

print(broadcasting_result)
>> [[ 1  2  3  4  5]
   [ 4  5  6  7  8]
   [ 7  8  9 10 11]]

print(strided_result)
>> [[ 1  2  3  4  5]
   [ 4  5  6  7  8]
   [ 7  8  9 10 11]]

Both approaches yield the desired subarray matrix effectively.

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