MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   如何在Matlab中计算单元格的唯一元素? (https://www.labfans.com/bbs/showthread.php?t=26583)

poster 2019-12-14 20:13

如何在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

[B]回答:[/B]

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

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

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

[url=https://stackoverflow.com/questions/5285217]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 09:16

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.