2015-04-02 51 views
0

我有一个单元阵列包含5个1x2阵列。有什么方法可以找到最重复的元素吗?我想我不能使用“模式”功能。我在网上查了一下,找不到解决问题的办法。每个人都一直在讨论带有字符串的单元阵列。MATLAB - 单元阵列的最重复元素

我使用的单元阵列是这样的: {[1 2],[2 5],[3 4],[1 2],[0 4]}

我想MATLAB找到[1 2]作为最重复的元素。

预先感谢您。

+0

你有这样的*统一的结构*单元阵列(每单元2个单元)为您的实际输入的数据? – Divakar 2015-04-02 20:08:44

+0

是的,数据是我的实际输入数据。 – theakt 2015-04-02 20:19:27

回答

1

对于统一的结构化单元阵列(每单元2个元件)的情况下

%// Convert the uniformly structured data to a 2D numeric array 
Anum = vertcat(A{:}) 

%// ID unique rows and ID all rows based on those 
[~,unqID,ID ] = unique(Anum,'rows') 

%// Use 'mode' on ID and then index into unqID to get the index of 
%// the most frequently occurring cell and finally index into the 
%// input cell array with that index to get the desired output 
out = A{unqID(mode(ID))} 

因此,对于给定输入数据 -

A = {[1 2], [2 5], [3 4], [1 2], [0 4]} 

你将不得不 -

out = 
    1  2 

与行的细胞更通用的情况下,向量

如果正在处理与在每个单元具有任意大小的行向量的单元阵列,则可以使用这种技术 -

%// Get all elements of A 
A_ele = [A{:}] 

%// Get lengths of each cell 
lens = cellfun('length',A) 

%// Setup a 2D numeric array corresponding to the input cell array 
A_num = zeros(max(lens),numel(lens))+max(A_ele)+1 
A_num(bsxfun(@ge,lens,[1:max(lens)]')) = A_ele %//' 

%// ID each row, find the mode with those & finally have the desired output 
[unqrows,unqID,ID ] = unique(A_num.','rows') %//' 
out = A{unqID(mode(ID))} 

因此,如果你必须输入作为 -

A = {[1 2], [2 5], [3 4], [1 2], [0 4], [1 2 1],[9],[7 2 6 3]} 

输出仍然是 -

out = 
    1  2 
+0

当我使用此代码时,输​​出为“1x2 double”。它不显示内部是什么。 – theakt 2015-04-02 20:26:26

+0

为什么不'out = {{unqID(mode(ID))}' – Daniel 2015-04-02 20:30:32

+1

@Daniel啊是的,OP需要一个数组作为输出,谢谢!编辑。 – Divakar 2015-04-02 20:32:17

0

这适用于一般单元阵列A

A = {[4 2] [2 5] [4 2] [1 2 1] [9] [7 2 6 3] [1 2 1] [1 2 1] [7 9]}; %// example data 
[ii, jj] = ndgrid(1:numel(A)); %// ii, jj describe all pairs of elements from A 
comp = cellfun(@isequal, A(ii), A(jj)); %// test each pair for equality 
[~, ind] = max(sum(comp,1)); %// get index of (first) most repeated element 
result = A{ii(ind)}; %// index into A to get result