0

My current solution to create a random matrix is

matrix = np.random.randint(low=n, high=m, size=(x,y))

Do you know a solution to not use an integer twice? Thank you

  • 1
    Does this answer your question? [Non-repetitive random number in numpy](https://stackoverflow.com/questions/8505651/non-repetitive-random-number-in-numpy) – Mr. T Dec 15 '20 at 23:11

2 Answers2

1

You could use np.random.choice.

np.random.choice(5, 3, replace=False)
# Output:
array([3,1,0]) # random
  • I tried this. But how is it possible to create a matrix not an array? – Jasper Schumacher Dec 15 '20 at 23:23
  • [Reshape your array?](https://stackoverflow.com/questions/30668223/how-to-change-array-shapes-in-in-numpy#30668375) – Mr. T Dec 15 '20 at 23:30
  • 2
    You could provide the size parameter as a tuple representing the dimensions of the matrix: `np.random.choice(5, size=(3, 5), replace=False)` creates a 3x5 matrix. – kaptankusto Dec 15 '20 at 23:37
0

If you don't want to use random choice, you can always just randomly pop from a list of integers.

import numpy as np
# define values 
n = 0
m = 20 
x = 3
y = 4 

integer_list = [i for i in range(n, m)]  # assuming m is exclusive 
matrix = np.zeros((x,y))
for i in range(x):
    for j in range(y):
        matrix[i][j] = integer_list.pop(np.random.randint(0, len(integer_list)))

Edit: I wasn't able to get it working with random choice. When I use random choice it returns a single value, rather than a list of values. A more efficient solution would be to simply shuffle the list.

import numpy as np
import random
# define values 
n = 0
m = 20 
x = 3
y = 4 

integer_list = [i for i in range(n, m)]  # assuming m is exclusive
random.shuffle(integer_list)
matrix = np.zeros((x,y))
for i in range(x):
    for j in range(y):
        matrix[i][j] = integer_list.pop()
alluppercase
  • 304
  • 1
  • 4
  • 12