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.
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:
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