如何在Matlab中计算单元格的唯一元素? [英] how to count unique elements of a cell in matlab?
本文介绍了如何在Matlab中计算单元格的唯一元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想计算Matlab中单元格数组的唯一元素.我怎样才能做到这一点?谢谢.
I want to count unique elements of a cell array in Matlab. How can I do this? Thank you.
c = {'a', 'b', 'c', 'a'};
% count unique elements, return the following struct
unique_count.a = 2
unique_count.b = 1
unique_count.c = 1
推荐答案
要计算唯一元素,可以组合唯一与 ACCUMARRAY >
To count unique elements, you can combine UNIQUE with 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);
To produce the structure, use NUM2CELL and STRUCT:
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
这篇关于如何在Matlab中计算单元格的唯一元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文