How can I generate a binary matrix of permutations
Show older comments
Hi, I'd like to ask for help on generating a binary matrix of permutations given several variables:
The first being the number of "ones" per row (n). The second being the length of each row (m). For example, if I was asked to generate a binary matrix given n = 2 and m = 4 the matrix generated should look like the following:
0011
0101
0110
1001
1010
1100
I've been asked to prepare a list of all permutations to select n=23 items out of a list of m=30.
I first thought of generating a matrix of binary numbers incrementing by 1:
0000
0001
0010
0011...
Then going through each row and checking the sum of ones. If that sum equals n then store that row vector in another variable and build my desired matrix that way. This is not efficient though. I am now thinking of something along the lines of this pseudo-code:
for i = 1 to 2^30
x = convert i to binary
if (count of ones in x) = n then y = x
I hope the problem is correctly phrased and I apologies for the simplicity of this question or if it has previously been asked - I'm a complete novice both in Matlab and in using this forum. Your help would be much appreciated.
Greg
2 Comments
jgg
on 14 Dec 2015
I think it might be easier to do an interative loop.
Start with like (in your example) 1100
Then iterate backwards by "moving" the rightmost-1 to the right.
1100
1010
1001
0110
0101
0011
You should be able to do this by recursion; that's definitely going to be better than try to perform billions of operations.
Greg
on 14 Dec 2015
Accepted Answer
More Answers (0)
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!