We’ll explore how to generate random matrices using the NumPy library in Python. Random matrices are commonly used in simulations, testing, and many other applications in data science and machine learning.
Using rand Method for Random Matrices
The np.random.rand function generates a matrix filled with random float numbers uniformly distributed between 0 and 1. You just need to specify the dimensions (number of rows and columns).
import numpy as np random_array = np.random.rand(3, 3) print(random_array)
As you can see, the matrix is filled with random float numbers between 0 and 1. You only need to specify the dimensions of the matrix.
Using randint Method for Random Integers
The np.random.randint function allows you to generate a matrix filled with random integers within a specified range. You can set both the lower and upper limits, as well as the size of the matrix.
import numpy as np random_array = np.random.randint(0, 7, size=10) print(random_array)
Based on this code you probably know. 0 is low value and 7 is max one. Size of array is 10.
You can also create multi-dimensional matrices by adjusting the size parameter:
random_matrix = np.random.randint(0, 10, size=(3, 3)) print(random_matrix)
Here, a 3×3 matrix is filled with random integers between 0 and 9.