0

I can easily create a random binary array in Numpy by doing this

random_mask = np.random.randint(0,2, (r, c))

But what what I actually want is to set the maximum number of 1s that can be in the array.

For example, if I want a 5,5 binary matrix, I want there to be at most 10 ones randomly placed throughout the matrix, and the rest are 0s.

I was thinking of an approach where I generate the random array like normal, count the number of 1s that are currently placed, and somehow subtracting off the ones I don't need.

I'm wondering if there's already a way to do this in numpy

1 Answer 1

1

This is the most basic approach I could think of:

import numpy as np

def binary_mask_random(r, c, n):
    a = np.zeros((r,c)).flatten()

    for i in range(np.random.randint(0, n+1)):
        x = np.random.randint(0, r*c)
        a[x] = 1

    return a.reshape((r,c))

It creates a 1xr*c array of zeros and fills it with up to n 1s at random positions. Returns a rxc array.

Sign up to request clarification or add additional context in comments.

4 Comments

hm yeah this would do the trick - I guess there isn't a built in way to do this in numpy? was trying to avoid loops
I don't think, that there is a built-in solution, but it may be possible to find a fully vectorized solution
yeah I’ll play around with it - thanks for pointing me in the right direction
@Carpetfizz Maybe you could also try np.random.choice([0, 1], (r, c), p=[0.9, 0.1]), but i'm not exactly sure, if this will always give you the exact results you need, because after all, it's just a probability

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.