w3resource

Creating and slicing a 1D NumPy array


19. Sub-matrix Strides in Reshaped Array

Write a NumPy program that creates a 1D array of 20 elements and use reshape() to create a (4, 5) matrix. Slice a (2, 3) sub-matrix and print its strides.

Sample Solution:

Python Code:

import numpy as np

# Step 1: Create a 1D array of 20 elements
original_1d_array = np.arange(20)
print("Original 1D array:\n", original_1d_array)

# Step 2: Reshape the 1D array into a (4, 5) matrix
reshaped_matrix = original_1d_array.reshape(4, 5)
print("\nReshaped (4, 5) matrix:\n", reshaped_matrix)

# Step 3: Slice a (2, 3) sub-matrix from the reshaped matrix
sub_matrix = reshaped_matrix[:2, :3]
print("\nSliced (2, 3) sub-matrix:\n", sub_matrix)

# Step 4: Print the strides of the sub-matrix
print("\nStrides of the sub-matrix:\n", sub_matrix.strides)

Output:

Original 1D array:
 [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]

Reshaped (4, 5) matrix:
 [[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]]

Sliced (2, 3) sub-matrix:
 [[0 1 2]
 [5 6 7]]

Strides of the sub-matrix:
 (20, 4)

Explanation:

  • Create a 1D array: A 1D array of 20 elements is created using np.arange(20).
  • Reshape to (4, 5) matrix: The 1D array is reshaped into a (4, 5) matrix.
  • Slice a sub-matrix: A (2, 3) sub-matrix is sliced from the reshaped matrix.
  • Print strides: The strides of the sub-matrix are printed.

For more Practice: Solve these Related Problems:

  • Write a NumPy program to extract various sub-matrices from a reshaped 1D array and analyze their strides.
  • Write a NumPy program to compare the strides of a sub-matrix obtained via slicing versus one obtained using np.take.
  • Write a NumPy program to create a 1D array, reshape it to a 2D matrix, then extract a non-contiguous sub-matrix and print its strides.
  • Write a NumPy program to slice a 2D array into multiple overlapping sub-matrices and display their strides for comparison.

Go to:


PREV : 2D to 3D Reshape Variation.
NEXT : NumPy Performance Optimization.

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.