How to create a matrix of random integers in python ?

Published: October 01, 2019

Tags: Python; Numpy; Random;

DMCA.com Protection Status

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}

Matrix (5,4) with positive and negative integers beetween -10 and 10

data = np.random.randint(-10,10, size=(5,4))

returns for example

array([[ -5,   2,   1, -10],
             [ -3,  -9, -10,   5],
             [ -6,  -2,   7,  -3],
             [  8,   2,   0,   4],
             [ -8,   3,  -5,   2]])

References

numpy.random.randint
Create random list of integers in Python
How to get array of random integers of non-default type in numpy