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.


For more Practice: Solve these Related Problems:

  • Create a 3x3 matrix with consecutive integers starting at 2 and ending at 10 using arithmetic progression.
  • Generate a 3x3 matrix from a range and then replace the center element with the average of its neighbors.
  • Construct a matrix with values from 2 to 10 and verify that each row increases by one from the previous element.
  • Generate a 3x3 matrix with sequential values and then transpose it to compare row and column order.

Go to:


PREV : Convert List to 1D Array
NEXT : Null Vector (10) & Update Sixth Value


Python-Numpy Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.