简体   繁体   English

MATLAB-细胞阵列最重复的元素

[英]MATLAB - A Cell Array's Most Repeated Element

I have a cell array containing 5 1x2 arrays. 我有一个包含5个1x2数组的单元格数组。 Is there any way to find the most repeated element? 有什么办法可以找到重复次数最多的元素? I think I cannot use the "mode" function. 我想我不能使用“模式”功能。 I looked it up on the internet and could not find a solution about the problem. 我在互联网上进行了查找,但找不到有关该问题的解决方案。 Everybody keeps talking about cells array with strings. 每个人都在谈论带有字符串的单元格数组。

The cell array I'm using is like this: {[1 2], [2 5], [3 4], [1 2], [0 4]} 我正在使用的单元格数组是这样的:{[1 2],[2 5],[3 4],[1 2],[0 4]}

I would like MATLAB to find [1 2] as the most repeated element. 我希望MATLAB找到[1 2]作为重复最多的元素。

Thank you in advance. 先感谢您。

For uniformly structured cell array (2 elements per cell) case 对于均匀结构的单元阵列(每个单元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))}

Thus, for the given input data - 因此,对于给定的输入数据-

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

You would have - 你将会拥有 -

out =
     1     2

More generic case with cells of row vectors 行向量像元的更一般情况

If you are dealing with a cell array that has arbitrary sized row vectors in each cell, you can use this technique - 如果要处理的单元格数组在每个单元格中具有任意大小的行向量,则可以使用此技术-

%// 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))}

Thus, if you have input as - 因此,如果输入为-

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

The output would still be - 输出仍然是-

out =
     1     2

This works for a general cell array A : 这适用于常规单元格数组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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM