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:
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:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Creating and reshaping a 2D NumPy array.
Next: NumPy Performance Optimization.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.