【问题标题】:MATLAB - A Cell Array's Most Repeated ElementMATLAB - 元胞数组中重复次数最多的元素
【发布时间】:2015-06-07 21:58:18
【问题描述】:

我有一个包含 5 个 1x2 数组的元胞数组。有没有办法找到重复次数最多的元素?我想我不能使用“模式”功能。我在互联网上查找了它,但找不到有关该问题的解决方案。每个人都在谈论带有字符串的单元格数组。

我使用的元胞数组是这样的: {[1 2]、[2 5]、[3 4]、[1 2]、[0 4]}

我希望 MATLAB 找到 [1 2] 作为重复次数最多的元素。

提前谢谢你。

【问题讨论】:

  • 您是否有这样一个结构一致的(每个单元格 2 个元素)单元格数组作为您的实际输入数据?
  • 是的,数据是我实际输入的数据。

标签: arrays matlab mode cell-array


【解决方案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

【讨论】:

  • 当我使用这段代码时,输​​出是“1x2 double”。它不显示里面的东西。
  • 为什么不out = A{unqID(mode(ID))}
  • @Daniel 啊,是的,OP 需要一个数字数组作为输出,谢谢!已编辑。
【解决方案2】:

这适用于一般元胞数组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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    相关资源
    最近更新 更多