w3resource

How to slice a Sub-array from a reshaped 1D NumPy array and print strides?


16. Sub-array Strides Inspection

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.

For more Practice: Solve these Related Problems:

  • Write a NumPy program to extract various sub-arrays from a reshaped array and print their strides to analyze the impact of slicing.
  • Write a NumPy program to create a 2D array, take a diagonal slice, and print its strides compared to the original array.
  • Write a NumPy program to extract a sub-array using slicing with a step and compare its strides with standard slicing.
  • Write a NumPy program to create a 2D array, perform multiple slices, and analyze how the strides change with each slicing operation.

Go to:


Previous: How to transpose a 2D NumPy array and print strides?
Next: Creating and reshaping a 4D NumPy array.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.