1

I am new to python. I want to write a function which generates a random nxm binary matrix with each value 0 for probability p.

What I did.

def randbin(M,N,P):              # function to generate random binary matrix    
    mat = (np.random.rand(M,N)>=P).astype(int)
    return mat  

y = randbin(5,4,0.3)

Every time I print the output, I didn't get the result as per the estimated probability. I don't know what I am doing wrong.

0

1 Answer 1

3

I don't see the problem with your method... A better way to generate a random matrix of 0s and 1s with a probability P of 0s is to use random.choice:

def randbin(M,N,P):  
    return np.random.choice([0, 1], size=(M,N), p=[P, 1-P])

To better understand, have a look at the random.choice documentation.

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

5 Comments

If it works, please don't forget to mark the post as answered by ticking the checkmark on the left of my answer (and welcome to stack)
Does the size is always a tuple. for example i wanted to create a binary matrix of size 100 in the above function. i.e. np.random.choice([0,1],size = (100). then it gave me an error: only length-1 arrays can be converted to Python scalar
tuples are for matrices. For a 100x100 matrix, use size=(100, 100). For an array of 100 elements, use size=100 or size=(100,).
Sometimes this won't work. I get equal 0's & 1's sometimes though I give unequal probability.
This is exactly what a probability will do ! When you flip a coin 10 times, you can have 10 faces, it happens. You need to read about probabilities if this behaviour troubles you.

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.