MATLAB: Sorting permutations of binary variables

binaryMATLABpermutationssorting

hi,
I have matrix representing all unique combinations of 6 binary variables:
N=6;
sZ=2^N;
vec = 0:sZ-1;
Z=dec2bin(vec);
Zl=double(reshape(logical(Z(:)-'0'),sZ,[]));
[~,sInx]=sort(sum(Zl,2),'ascend');
Zls=Zl(sInx,:);
Zls(1,:)=[]
Zls =
0 0 0 0 0 1
0 0 0 0 1 0
0 0 0 1 0 0
0 0 1 0 0 0
0 1 0 0 0 0
1 0 0 0 0 0
0 0 0 0 1 1
0 0 0 1 0 1
(...)
1 1 1 1 0 1
1 1 1 1 1 0
1 1 1 1 1 1
My goal is to have this matrix sorted in the following way:
  • Start with unit row vectors:
1 0 0 0 0 0
0 1 0 0 0 0
..
  • Then have all row vectors with two ones, starting with row vectors that start with 1 in column 1 (and continuing with rows where 1 starts in column 2 etc)
1 1 0 0 0 0
1 0 1 0 0 0
1 0 0 1 0 0
(...)
0 1 1 0 0 0
0 1 0 1 0 0
(...)
0 0 1 1 0 0
0 0 1 0 1 0
etc
  • Then have all row vectors with three ones, starting with row vectors that start with 1 in colum 1 …
1 1 1 0 0 0
1 0 1 1 0 0
1 0 0 1 1 0
etc. etc.
Until the last row is
1 1 1 1 1 1
Any advice either on how to sort the matrix Zls above or on how to generate this sorted matrix directly would be appreciated! Thank you for your help!

Best Answer

Try this
N=6;
A = repmat({[0,1]}, 1, N);
M = combvec(A{:}).';
M(1, :) = [];
grps = splitapply(@(x) {x}, M, sum(M,2));
Z = cellfun(@(x) {flipud(sortrows(x))}, grps);
Z = vertcat(Z{:});
Result
>> Z
Z =
1 0 0 0 0 0
0 1 0 0 0 0
0 0 1 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1
1 1 0 0 0 0
1 0 1 0 0 0
1 0 0 1 0 0
1 0 0 0 1 0
1 0 0 0 0 1
0 1 1 0 0 0
0 1 0 1 0 0
0 1 0 0 1 0
0 1 0 0 0 1
0 0 1 1 0 0
0 0 1 0 1 0
0 0 1 0 0 1
0 0 0 1 1 0
0 0 0 1 0 1
0 0 0 0 1 1
1 1 1 0 0 0
1 1 0 1 0 0
1 1 0 0 1 0
1 1 0 0 0 1
1 0 1 1 0 0
1 0 1 0 1 0
1 0 1 0 0 1
1 0 0 1 1 0
1 0 0 1 0 1
1 0 0 0 1 1
0 1 1 1 0 0
0 1 1 0 1 0
0 1 1 0 0 1
0 1 0 1 1 0
0 1 0 1 0 1
0 1 0 0 1 1
0 0 1 1 1 0
0 0 1 1 0 1
0 0 1 0 1 1
0 0 0 1 1 1
1 1 1 1 0 0
1 1 1 0 1 0
1 1 1 0 0 1
1 1 0 1 1 0
1 1 0 1 0 1
1 1 0 0 1 1
1 0 1 1 1 0
1 0 1 1 0 1
1 0 1 0 1 1
1 0 0 1 1 1
0 1 1 1 1 0
0 1 1 1 0 1
0 1 1 0 1 1
0 1 0 1 1 1
0 0 1 1 1 1
1 1 1 1 1 0
1 1 1 1 0 1
1 1 1 0 1 1
1 1 0 1 1 1
1 0 1 1 1 1
0 1 1 1 1 1
1 1 1 1 1 1
Related Question