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

Mar*_*n08 2 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
Run Code Online (Sandbox Code Playgroud)

Jon*_*nas 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); 
Run Code Online (Sandbox Code Playgroud)

要生成结构,请使用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
Run Code Online (Sandbox Code Playgroud)