How to reshape and modify a 1D NumPy array to a 3x3 matrix?
Write a NumPy program that creates a 1D array of 9 elements and reshape it into a 3x3 matrix. Modify the matrix and observe the changes in the original array.
Sample Solution:
Python Code:
import numpy as np
# Create a 1D array of 9 elements
array_1d = np.arange(1, 10)
# Reshape the 1D array into a 3x3 matrix
matrix_3x3 = array_1d.reshape(3, 3)
# Modify the matrix
matrix_3x3[0, 0] = 99
# Print the modified matrix
print("Modified matrix:\n", matrix_3x3)
# Print the original 1D array to observe changes
print("Original 1D array after modification:", array_1d)
Output:
Modified matrix: [[99 2 3] [ 4 5 6] [ 7 8 9]] Original 1D array after modification: [99 2 3 4 5 6 7 8 9]
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 9 elements using np.arange(1, 10).
- Reshape to a 3x3 matrix: We reshape the 1D array to a 3x3 matrix matrix_3x3 using reshape().
- Modify the matrix: We change the first element of the matrix to 99.
- Print the modified matrix: We print the modified matrix to see the change.
- Observe changes in the original array: We print the original 1D array to observe that the modification in the matrix also affects the original array since they share the same data.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics