我想在Matlab中计算单元格数组的唯一元素。我怎样才能做到这一点?谢谢。
c = {'a', 'b', 'c', 'a'};
% count unique elements, return the following struct
unique_count.a = 2
unique_count.b = 1
unique_count.c = 1
答案 0 :(得分:7)
要计算唯一元素,您可以将UNIQUE与ACCUMARRAY
结合使用c = {'a', 'b', 'c', 'a'};
[uniqueC,~,idx] = unique(c); %# uniqueC are unique entries in c
%# replace the tilde with 'dummy' if pre-R2008a
counts = accumarray(idx(:),1,[],@sum);
countCell = num2cell(counts);
tmp = [uniqueC;countCell']; %'
unique_count = struct(tmp{:}) %# this evaluates to struct('a',2,'b',1,'c')
unique_count =
a: 2
b: 1
c: 1
答案 1 :(得分:1)
在文件交换中查看count_unique。它使用accumarray
或sort
,具体取决于哪个最合适。它还会检查nans / infs。