nattys
nattys

Reputation: 235

Selecting random position in numpy matrix

I have a numpy matrix that is randomly populated with zeros and ones:

grid = np.random.binomial(1, 0.2, size = (3,3))

Now I need to pick a random position inside this matrix and turn it to 2

I tried:

pos = int(np.random.randint(0,len(grid),1))

But then I get an entire row filled with 2s. How do I pick only one random position? Thank you

Upvotes: 1

Views: 3989

Answers (1)

eapetcho
eapetcho

Reputation: 527

The issue with your code is that you're just requesting only one random value for the indices instead of two random numbers (random). This one way of achieving your goal:

# Here is your grid
grid = np.random.binomial(1, 0.2, size=(3,3))

# Request two random integers between 0 and 3 (exclusive)
indices =  np.random.randint(0, high=3, size=2)

# Extract the row and column indices
i = indices[0]
j = indices[1]

# Put 2 at the random position
grid[i,j] = 2   

Upvotes: 3

Related Questions