How can I create a random binary matrix with a specified number of 1's and 0's?
20 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Jan
on 26 Jul 2013
Edited: Jan
on 26 Jul 2013
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.
1 Comment
Aryama Mandal
on 14 Apr 2015
what will be the code if n=1, as this code is not running in case of n=1
More Answers (3)
Lotanna Ohazuruike
on 25 Feb 2021
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!
0 Comments
Jan
on 26 Jul 2013
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.
0 Comments
See Also
Categories
Find more on Random Number Generation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!