w3resource

NumPy: Create a 3x4 matrix filled with values ​​from 10 to 21

NumPy: Basic Exercise-25 with Solution

Write a NumPy program to create a 3x4 matrix filled with values ​​from 10 to 21.

Sample Solution :

Python Code :

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

# Creating a NumPy array 'm' containing integers from 10 to 21 and reshaping it into a 3x4 matrix using np.arange() and .reshape()
m = np.arange(10, 22).reshape((3, 4))

# Printing the array 'm' representing a 3x4 matrix
print(m) 

Sample Output:

[[10 11 12 13]
 [14 15 16 17]
 [18 19 20 21]]                         

Explanation:

In the above code np.arange() function creates a NumPy array containing integers from 10 to 21. The np.arange() function generates an array of evenly spaced values within a specified interval. In this case, it generates an array starting at 10 and ending before 22, with a default step size of 1, resulting in an array of integers from 10 to 21. Then, the reshape() method is used to change the shape of the generated array into a 3x4 matrix (3 rows and 4 columns).

Finally print(m) prints the reshaped array 'm' to the console. The output will be a 3x4 matrix containing integers from 10 to 21 arranged in the specified shape:

Pictorial Presentation:

NumPy: Create a 3x4 matrix filled with values ​​from 10 to 21.

Python-Numpy Code Editor:

Previous: NumPy program to multiply the values ​​of two given vectors.
Next: NumPy program to find the number of rows and columns of a given matrix.

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.