w3resource

How to reshape and modify a 1D NumPy array to a 3x3 matrix?

NumPy: Memory Layout Exercise-9 with Solution

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:

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

Previous: How to flatten a 3D NumPy array and print its Strides?
Next: How to change memory layout of a 2D NumPy array to C order?

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/reshape-and-modify-a-1d-numpy-array-to-a-3-3-matrix.php