faster function than unique for cell arrays
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (1)
Jan
el 19 de Ag. de 2012
Editada: Jan
el 26 de Sept. de 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 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!