faster function than unique for cell arrays

3 ビュー (過去 30 日間)
Danielle Leblanc
Danielle Leblanc 2012 年 8 月 6 日
編集済み: Jan 2017 年 9 月 26 日
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.

回答 (1 件)

Jan
Jan 2012 年 8 月 19 日
編集済み: Jan 2017 年 9 月 26 日
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.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by