How can I create a random binary matrix with a specified number of 1's and 0's?

fi = 1/3
x = randi([0 1],1,9);
while (mean(x)~= fi)
x = randi([0 1],1,9);
end
This finds a random 3 x 3 binary matrix with 3 ones, but for a 4x4 matrix and larger this can take forever.
Basically what I'm trying to do is find all possible combinations of a m x n binary matrix with a specified number of 1's.

 Accepted Answer

n = 3;
a = zeros(5, 6);
a(randperm(numel(a), n)) = 1;
Or for older Matlab versions, which do not support RANDPERM with 2 inputs:
index = randperm(numel(a));
a(index(1:n)) = 1;
For both methods you get a zero matrix with exactly n ones.
But for your goal to count the number of possible combinations this approach is extremely bad. There are 2^(5*6) different binary [5x6] matrices.

More Answers (3)

Here's a neat trick I use.
r4 = rand(15,15); % generates uniformly distributed random number 15x15 array
r4(r4>0.3) = 1; % sets every element with a value greater than 0.3 to become 1
r4(r4<=0.3) = 0; % sets every element with a value less than or equal to 0.3 to become 0
Hope that helps!
a=zeros(5);
n=3 % number of 1
a(randi(numel(a),3,1))=1

5 Comments

There is a high chance that RANDI replied repeated values.
But this drawback remains in the method you suggest. Do you post it because the chance to get repetitions in randi(numel(a),3,1) is at least smaller than to get exactly 3 ones in randi([0 1], 4, 4)?
Sometimes this will return a matrix with only two 1's. Any idea why this is?
Oh ok it's because randi gave repeated values.

Sign in to comment.

Another solution which works until matrices with 52 elements:
M = 5;
N = 6;
d = rem(floor(rand * 2^52 * pow2(-51:0)), 2);
a = reshape(d(1:M*N), M, N);
Now you get the bit representation of a random number between 0 and 2^52.

Categories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!