MATLAB: Produce all combinations of n choose k in binary

find all combinations of n choose k in binary

I have
n=5;
k=3;
I want to have combinations of n choose k in binary
result should be (5 choose 3=10) (the order does not matter)
A=[1 0 0 1 1;
1 1 1 0 0;
1 0 1 0 1;
1 0 1 1 0;
0 0 1 1 1;
0 1 1 1 0;
0 1 1 0 1;
1 1 0 0 1;
0 1 1 0 1;
0 1 0 1 1;
]

Best Answer

This is easier than you may think, as long as you think outside of the box just a bit.
n = 5;
k = 3;
dec2bin(sum(nchoosek(2.^(0:n-1),k),2)) - '0'
ans =
0 0 1 1 1
0 1 0 1 1
1 0 0 1 1
0 1 1 0 1
1 0 1 0 1
1 1 0 0 1
0 1 1 1 0
1 0 1 1 0
1 1 0 1 0
1 1 1 0 0
The nice thing is, you do not need to generate a long list of all binary numbers, then keep only those that have exactly three bits turned on.
The above scheme should work for up to 52 bit results, since MATLAB can encode integers as large as 2^53-1 in a double. And, of course, if k is at all large, then things will get nasty for n>52. Anyway, I don't think dec2bin will be successful in more than 52 bits though, even if you tried to use uint64.