Binary matrix that contains specific number of zeros in each row

4 views (last 30 days)
Hi,
I want to produce a matrix of n columns that contains only 1 and 0, it should produce all possible combinations and non-repeatable. I used ff2n(n) to produce this matrix, but now I want to control the number of zeros. Cause If n=46, the ff2n(46) matrix is too big and exceeds array size preference, I need to cut the matrix. So is there any algorithm allow me to control the number of zeros in the binary matrix?
For example
ff2n(4)
ans =
0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1
and my desired results which contains up to two 0 are:
ans =
0 0 1 1
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1
How could I solve this? Could anyone help me with this please?

Accepted Answer

John D'Errico
John D'Errico on 24 Jul 2019
Edited: John D'Errico on 24 Jul 2019
At most 2 zeros out of 4 is easy.
nchoosek(4,0) + nchoosek(4,1) + nchoosek(4,2)
ans =
11
So 11 possibilities. If the numbers get larger, then it will still be very nasty. So 50 columns, with as many as 10 zeros is still on the order 1e10 rows in that matrix, and a total memory required on the order of 4e12 bytes (4 terabytes of RAM, just to store that array.) You would not be able to do this.
But for reasonable problems where I will not create the full factorial as it is too large for you, it is easy enough. Just do it constructively. A loop will be sufficient here.
ncols = 4;
nzmax = 2;
mat = ones(1,ncols);
for n = 1:nzmax
zloc = nchoosek(1:ncols,n);
m = size(zloc,1);
matn = ones(m,ncols);
matn(sub2ind(size(matn),repmat((1:m)',[1,n]),zloc)) = 0;
mat = [mat;matn];
end
mat
mat =
1 1 1 1
0 1 1 1
1 0 1 1
1 1 0 1
1 1 1 0
0 0 1 1
0 1 0 1
0 1 1 0
1 0 0 1
1 0 1 0
1 1 0 0

More Answers (0)

Categories

Find more on Linear Algebra 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!