w3resource

NumPy: Create a 3x3 matrix with values ranging from 2 to 10

NumPy: Array Object Exercise-3 with Solution

Create 3x3 Matrix (2–10)

Write a NumPy program to create a 3x3 matrix with values ranging from 2 to 10.

Python NumPy: Create a 3x3 matrix with values ranging from 2 to 10

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a NumPy array 'x' using arange() from 2 to 11 and reshaping it into a 3x3 matrix
x = np.arange(2, 11).reshape(3, 3)

# Printing the resulting 3x3 matrix 'x'
print(x)

Sample Output:

[[ 2  3  4]                                                             
 [ 5  6  7]                                                             
 [ 8  9 10]]

Explanation:

In the above code -

np.arange(2, 11): Creates a one-dimensional NumPy array containing integers from 2 (inclusive) to 11 (exclusive), i.e., [2, 3, 4, 5, 6, 7, 8, 9, 10].

.reshape(3,3): Reshapes the one-dimensional NumPy array into a 3x3 two-dimensional array.

print(x): Prints the 3x3 NumPy array.

Python-Numpy Code Editor:

Previous: Write a NumPy program to convert a list of numeric value into a one-dimensional NumPy array.
Next: Write a NumPy program to create a null vector of size 10 and update sixth value to 11.

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://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-3.php