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.
This problem involves writing a NumPy program to generate a 3x4 matrix filled with consecutive values starting from 10 and ending at 21. The task requires utilizing NumPy's array creation functionalities to efficiently construct the matrix with the specified range of values while maintaining the desired dimensions.
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)
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:
Visual Presentation:
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.
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://w3resource.com/python-exercises/numpy/basic/numpy-basic-exercise-25.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics