1

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

2
  • 3
    Select any random position or any random position that is also 1 or any random position that is also 0? For the former simply do : np.put(grid,np.random.choice(grid.size),2). Commented Oct 13, 2017 at 16:52
  • Any random position. Your solution works. Thank you. Commented Oct 13, 2017 at 17:01

1 Answer 1

3

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   
Sign up to request clarification or add additional context in comments.

1 Comment

Your solution helped me solve another problem in my code that I had no idea was related to the lack of indices. Thank you so much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.