LINE Solver
MATLAB API documentation
Loading...
Searching...
No Matches
uniqueperms.m
1function pu = uniqueperms(vec)
2% list of all unique permutations of a vector with (possibly) replicate elements
3% usage: pu = uniqueperms(vec)
4%
5% arguments: (input)
6% vec - 1xn or nx1 vector of elements, replicates allowed
7%
8% arguments: (output)
9% pu - mxn array of permutations of vec. Each row is a permutation.
10%
11% The result should be the same as unique(perms(vec),'rows')
12% (although the order may be different.)
13%
14% Example:
15% pu = uniqueperms([1 1 1 2 2])
16% pu =
17% 1 1 1 2 2
18% 1 1 2 2 1
19% 1 1 2 1 2
20% 1 2 1 2 1
21% 1 2 1 1 2
22% 1 2 2 1 1
23% 2 1 1 2 1
24% 2 1 1 1 2
25% 2 1 2 1 1
26% 2 2 1 1 1
27%
28% See also: unique, perms
29%
30% Author: John D'Errico
31% e-mail: woodchips@rochester.rr.com
32% Release: 1.0
33% Release date: 2/25/08
34
35% How many elements in vec?
36vec = vec(:); % make it always a column vector
37n = length(vec);
38
39% how many unique elements in vec?
40uvec = unique(vec);
41nu = length(uvec);
42
43% any special cases?
44if isempty(vec)
45 pu = [];
46elseif nu == 1
47 % there was only one unique element, possibly replicated.
48 pu = vec';
49elseif n == nu
50 % all the elements are unique. Just call perms
51 pu = perms(vec);
52else
53 % 2 or more elements, at least one rep
54 pu = cell(nu,1);
55 for i = 1:nu
56 v = vec;
57 ind = find(v==uvec(i),1,'first');
58 v(ind) = [];
59 temp = uniqueperms(v);
60 pu{i} = [repmat(uvec(i),size(temp,1),1),temp];
61 end
62 pu = cell2mat(pu);
63end
64end