How to slice a Sub-array from a reshaped 1D NumPy array and print strides?
NumPy: Memory Layout Exercise-16 with Solution
Write a NumPy program that creates a 1D array of 15 elements, reshape it into a (3, 5) matrix, then slice a sub-array from it and print the sub-array and its strides.
Sample Solution:
Python Code:
import numpy as np
# Create a 1D array of 15 elements
array_1d = np.arange(1, 16)
# Reshape the 1D array into a (3, 5) matrix
matrix_3x5 = array_1d.reshape(3, 5)
# Slice a sub-array from the matrix (e.g., select rows 1 and 2, columns 2 to 4)
sub_array = matrix_3x5[1:3, 2:5]
# Print the sub-array
print("Sub-array:\n", sub_array)
# Print the strides of the sub-array
print("Strides of the sub-array:", sub_array.strides)
Output:
Sub-array: [[ 8 9 10] [13 14 15]] Strides of the sub-array: (20, 4)
Explanation:
- Import NumPy library: We start by importing the NumPy library to handle array operations.
- Create a 1D array: We create a 1D array array_1d with 15 elements using np.arange(1, 16).
- Reshape to (3, 5) matrix: We reshape the 1D array to a (3, 5) matrix matrix_3x5 using reshape().
- Slice a sub-array: We slice a sub-array from matrix_3x5 by selecting rows 1 and 2, and columns 2 to 4, resulting in sub_array.
- Print the sub-array: We print sub_array to display the sliced portion of the original matrix.
- Print strides of sub-array: We print the strides of sub_array using the strides attribute to understand its memory layout.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: How to transpose a 2D NumPy array and print strides?
Next: Creating and reshaping a 4D NumPy array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/numpy/slice-a-sub-array-from-a-reshaped-1d-numpy-array-and-print-strides.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics