w3resource

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


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: