-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathunique_stable.m
70 lines (46 loc) · 2.28 KB
/
unique_stable.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
function [c,indA,indC] = unique_stable( a )
% 'stable' flag of "unique" matlab function appeared after R2012. So here
% we use a part of this R2012 code, for cross-version compatibility.
% Real syntax ( matlab version >= R2012 ) should be :
% [c,indA,indC] = unique( a , 'stable' )
%% Check input arguments
% narginchk(1,1)
% narginchk introduced in R2011b
if nargin ~= 1
error('%s uses one and only one input argument',mfilename)
end
validateattributes(a,{'cell'},{'column'},mfilename,'cellColumn',1)
%% Filter
numelA = numel(a);
% Sort A and get indices.
[sortA,indSortA] = sort(a);
% groupsSortA indicates the location of non-matching entries.
groupsSortA = ~strcmp(sortA(1:end-1),sortA(2:end));
groupsSortA = groupsSortA(:);
groupsSortA = [true;groupsSortA]; % First element is always a member of unique list.
% Extract unique elements
invIndSortA = indSortA;
invIndSortA(invIndSortA) = 1:numelA; % Find inverse permutation.
logIndA = groupsSortA(invIndSortA); % Create new logical by indexing into groupsSortA.
c = a(logIndA); % Create unique list by indexing into unsorted a.
% Find indA.
indA = find(logIndA); % Find the indices of the unsorted logical.
% Find indC.
if isempty(a)
indC = zeros(0,1);
else
[~,indSortC] = sort(c); % Sort C to get index.
lengthGroupsSortA = diff(find([groupsSortA; true])); % Determine how many of each of the above indices there are in IC.
diffIndSortC = diff(indSortC); % Get the correct amount of each index.
diffIndSortC = [indSortC(1); diffIndSortC];
indLengthGroupsSortA = cumsum([1; lengthGroupsSortA]);
indLengthGroupsSortA(end) = [];
indCOrderedBySortA(indLengthGroupsSortA) = diffIndSortC; % Since indCOrderedBySortA is not already established as a column,
indCOrderedBySortA = indCOrderedBySortA.'; % it becomes a row and that it needs to be transposed.
if sum(lengthGroupsSortA) ~= length(indCOrderedBySortA);
indCOrderedBySortA(sum(lengthGroupsSortA)) = 0;
end
indCOrderedBySortA = cumsum(indCOrderedBySortA);
indC = indCOrderedBySortA(invIndSortA); % Reorder the list of indices to the unsorted order.
end
end