w3resource

Creating and slicing a 1D NumPy array

NumPy: Memory Layout Exercise-19 with Solution

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.

Python-Numpy Code Editor:

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

Previous: Creating and reshaping a 2D NumPy array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://w3resource.com/python-exercises/numpy/creating-and-slicing-a-1d-numpy-array.php