faster function than unique for cell arrays
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi,
I have a slow loop mainly because i use unique(A) where A is a cell array (these are the profiler's analysis). I am wondering if there is a faster unique function for cell arrays.
0 commentaires
Réponses (1)
Jan
le 19 Août 2012
Modifié(e) : Jan
le 26 Sep 2017
It depends on the contents of the cell. If you are talking of a cell string, this could be faster for short (< 1000) elements:
function [AA, AI, BI] = CStrUnique(A)
nA = numel(A);
if nA > 1
[As, SV] = sort(A(:));
if nargout < 3
UV(SV) = [1; strcmp(As(2:nA), As(1:nA - 1)) == 0];
AI = find(UV);
else % Indices requested:
UV = [1; strcmp(As(2:nA), As(1:nA - 1)) == 0];
UVs(SV) = UV;
AI = find(UVs);
% Complex creation of BI so that AA(BI) == A:
v = zeros(1, nA);
v(AI) = 1:length(AI); % Sequence related to AA
vs = v(SV); % Sorted like A
vf = vs(find(vs)); %#ok<FNDSB> % Just the filled entries
BI(SV) = vf(cumsum(UV)); % Inflate multiple elements
end
elseif nA % Comparison of subsequent elements fails for nA == 1
AI = 1;
BI = 1;
else
AI = [];
BI = [];
end
AA = A(AI);
It does not change the sorting order in opposite to UNIQUE. A C-Mex function could be even faster. But before further speculations, it would be helpful if you specify the type and size of the input at first.
A version for numerical input and stable sorting: https://www.mathworks.com/matlabcentral/answers/357818-interpolation-vector-with-a-lot-of-duplicate-values-code-on-r2010a#answer_282652
0 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!