Interesting problem. I used a slightly more complex example, with two values duplicated (4 twice, 9 thrice), for which we would expect twelve possible permutations:
>> a = [1,4;2,9;3,2;4,9;5,4;6,9]
a =
1 4
2 9
3 2
4 9
5 4
6 9
And the code:
[N,B] = histc(a(:,2),unique(a(:,2)));
X = find(N>1);
foo = @(x)perms(find(B==x));
C = arrayfun(foo,X,'uni',0);
S = cellfun('size',C,1);
L = arrayfun(@(r)1:r,S,'uni',0);
[L{:}] = ndgrid(L{:});
R = cellfun(@(v)v(:),L,'uni',0);
baz = @(m,r)m(r,:);
M = cellfun(baz,C,R,'uni',0);
V = 1:size(a,1);
Z = cell(1,prod(S));
for ii = 1:prod(S)
for jj = 1:numel(X)
V(B==X(jj)) = M{jj}(ii,:);
end
Z{ii} = a(V,:);
end
And checking the output:
>> numel(Z)
ans = 12
>> Z{:}
ans =
1 4
2 9
3 2
4 9
5 4
6 9
ans =
5 4
2 9
3 2
4 9
1 4
6 9
ans =
1 4
4 9
3 2
2 9
5 4
6 9
ans =
5 4
4 9
3 2
2 9
1 4
6 9
ans =
1 4
2 9
3 2
6 9
5 4
4 9
ans =
5 4
2 9
3 2
6 9
1 4
4 9
ans =
1 4
4 9
3 2
6 9
5 4
2 9
ans =
5 4
4 9
3 2
6 9
1 4
2 9
ans =
1 4
6 9
3 2
2 9
5 4
4 9
ans =
5 4
6 9
3 2
2 9
1 4
4 9
ans =
1 4
6 9
3 2
4 9
5 4
2 9
ans =
5 4
6 9
3 2
4 9
1 4
2 9
Note that the number of permutations is (# of 1st duplicate value)! * (# of 2nd duplicate value)! * (# of 3rd duplicate value)! * ... , which will clearly explode very quickly into something totally intractable....
Best Answer