如何在matlab中计算单元格的唯一元素?

时间:2011-03-12 20:17:21

标签: matlab

我想在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

2 个答案:

答案 0 :(得分:7)

要计算唯一元素,您可以将UNIQUEACCUMARRAY

结合使用
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); 

要制作结构,请使用NUM2CELLSTRUCT

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。它使用accumarraysort,具体取决于哪个最合适。它还会检查nans / infs。