PDA

查看完整版本 : 如何在Matlab中计算单元格的唯一元素?


poster
2019-12-14, 20:13
我想计算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

回答:

要计算唯一元素,可以将UNIQUE (http://www.mathworks.com/help/techdoc/ref/UNIQUE.html)与ACCUMARRAY (http://www.mathworks.com/help/techdoc/ref/ACCUMARRAY.html)结合使用

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); 要生成结构,请使用NUM2CELL (http://www.mathworks.com/help/techdoc/ref/NUM2CELL.html)和STRUCT (http://www.mathworks.com/help/techdoc/ref/struct.html) :

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

更多&回答... (https://stackoverflow.com/questions/5285217)