How to create and change Strides of a 2D NumPy array?
5. 2D Array Stride Modification
Write a NumPy program to create a 2D array of shape (5, 5) and change its strides to view every other element in the first dimension.
Sample Solution:
Python Code:
import numpy as np
# Create a 2D array of shape (5, 5)
array_2d = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]])
# Change the strides to view every other element in the first dimension
strided_array = array_2d[::2, :]
# Print the strided array
print(strided_array)
Output:
[[ 1 2 3 4 5] [11 12 13 14 15] [21 22 23 24 25]]
Explanation:
- Import NumPy library: We start by importing the NumPy library to handle array operations.
- Create a 2D array: We create a 2D array array_2d of shape (5, 5) using np.array().
- Change the strides: We use slicing with strides ::2 to view every other element in the first dimension, resulting in strided_array.
- Print the result: Finally, we print the strided_array.
For more Practice: Solve these Related Problems:
- Write a NumPy program to create a 2D array and use slicing with a step to simulate stride modification by selecting every other row.
- Write a NumPy program to use np.lib.stride_tricks.as_strided on a 2D array to create a view that skips elements in the first dimension.
- Write a NumPy program to generate a sub-array from a 2D array with custom strides and print its shape and memory layout.
- Write a NumPy program to compare the results of slicing with steps and an as_strided view for obtaining alternate rows from a 2D array.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.Previous: How to create and reshape a 3D NumPy array using ravel()?
Next: How to reshape a 1D NumPy array to multiple dimensions?
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics