How to create a matrix of random integers in python ?

Daidalos October 01, 2019


To create a matrix of random integers in python, a solution is to use the numpy function randint, examples:

1D matrix with random integers between 0 and 9:

Example of 1D matrix with 20 random integers between 0 and 9:

>>> import numpy as np
>>> A = np.random.randint(10, size=(20))
>>> A
array([1, 8, 4, 3, 5, 7, 1, 2, 9, 6, 7, 6, 3, 1, 4, 6, 4, 9, 9, 6])

returns for example:

\begin{equation}
A = \left( \begin{array}{ccc}
1 & 8 & 4 & 3 & 5 & 7 & 1 & 2 & 9 & 6 & 7 & 6 & 3 & 1 & 4 & 6 & 4 & 9 & 9 & 6
\end{array}\right)
\end{equation}

Matrix (2,3) with random integers between 0 and 9

>>> import numpy as np
>>> A = np.random.randint(10, size=(2, 3))
>>> A
array([[1, 4, 3],
       [5, 1, 8]])

returns for example:

\begin{equation}
A = \left( \begin{array}{ccc}
1 & 4 & 3 \\
5 & 1 & 8
\end{array}\right)
\end{equation}

Matrix (4,4) with random integers between 0 and 1

>>> import numpy as np
>>> A = np.random.randint(2, size=(4,4))
>>> A
array([[0, 0, 1, 1],
       [1, 0, 0, 0],
       [0, 0, 1, 1],
       [0, 0, 1, 1]])

returns for example:

\begin{equation}
A = \left( \begin{array}{cccc}
0 & 0 & 1 & 1 \\
1 & 0 & 0 & 0 \\
0 & 0 & 1 & 1 \\
0 & 0 & 1 & 1
\end{array}\right)
\end{equation}

References

Links Site
numpy.random.randint doc scipy
Create random list of integers in Python stackoverflow
How to get array of random integers of non-default type in numpy stackoverflow

Licence


Activity


Google Ads