# How to create a matrix of random integers in python ?

Published: October 01, 2019

Tags: Python; Numpy; Random;

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:

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)

### 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:

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

### 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:

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

### 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]])