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
Release: 2024-12-02 18:18:11
Original
1087 people have browsed it

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)]
Copy after login

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))
Copy after login

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])
Copy after login

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)
Copy after login

Both approaches will produce the following result:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template