Home >Backend Development >Python Tutorial >How to Efficiently Extract Subarrays with a Specific Stride in NumPy?

How to Efficiently Extract Subarrays with a Specific Stride in NumPy?

Susan Sarandon
Susan SarandonOriginal
2024-12-06 09:41:11813browse

How to Efficiently Extract Subarrays with a Specific Stride in NumPy?

Extracting Subarrays with Stride Using NumPy

Given a NumPy array, it is often necessary to partition it into subarrays with specific strides. This question explores how to achieve this efficiently using broadcasting and NumPy strides.

Solution 1: Broadcasting

The broadcasting_app function employs broadcasting to construct the desired subarrays. It calculates the number of rows based on the array's size, the subarray length, and the stride. It then uses broadcasting to create a new array where each row represents a subarray.

Solution 2: NumPy Strides

The strided_app function utilizes NumPy's efficient stride handling mechanism. It calculates the number of rows and strides as before. Then, it leverages the as_strided function to create a new array with the desired strides and shape.

Sample Usage

To illustrate these solutions, consider the following Python code:

import numpy as np

a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
L = 5  # Subarray length
S = 3  # Stride

print(broadcasting_app(a, L, S))
print(strided_app(a, L, S))

Output:

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

Both approaches produce the desired subarray matrix efficiently.

The above is the detailed content of How to Efficiently Extract Subarrays with a Specific Stride 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