faster function than unique for cell arrays

3 Ansichten (letzte 30 Tage)
Danielle Leblanc
Danielle Leblanc am 6 Aug. 2012
Bearbeitet: Jan am 26 Sep. 2017
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.

Antworten (1)

Jan
Jan am 19 Aug. 2012
Bearbeitet: Jan am 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.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by