How can I create a random binary matrix with a specified number of 1's and 0's?
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.
Accepted Answer
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!
Azzi Abdelmalek
on 26 Jul 2013
a=zeros(5);
n=3 % number of 1
a(randi(numel(a),3,1))=1
5 Comments
Jan
on 26 Jul 2013
There is a high chance that RANDI replied repeated values.
Azzi Abdelmalek
on 26 Jul 2013
Exact
Jan
on 26 Jul 2013
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)?
Nick Suttell
on 29 Jul 2013
Nick Suttell
on 29 Jul 2013
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.
Categories
Find more on Creating and Concatenating Matrices 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!