简体   繁体   English

在MATLAB中的向量中找到10个最重复的元素

[英]Find 10 most repeated elements in a vector in MATLAB

I'm suppose to find 10 most repeated elements in a vector with n elements, 我想在n元素的向量中找到10最重复的元素,

(the elements are from 1-100 ) (元素来自1-100

does anyone know how to do that? 有谁知道这是怎么做到的吗?

I know how to find the one that is most repeated element in a vector but I don't know how to find 10 most repeated elements with n being unknown. 我知道如何在向量中找到最重复元素的那个,但我不知道如何找到10个最重复的元素,其中n是未知的。

a = randi(10,1,100);
y = hist(a,1:max(a));
[~,ind] = sort(y,'descend');
out = ind(1:10);

for number of occurrences use y(ind(1:10)) . 对于出现次数,请使用y(ind(1:10))

I had some doubts so I tested it many times, it seems to work. 我有些疑惑,所以我测试了很多次,它似乎工作。

You can use unique for that case. 你可以在这种情况下使用unique In my example, I have 4 numbers and I want to grep the 2 with the most occurances. 在我的例子中,我有4个数字,我想要发现最多的2。

A = [1 1 3 3 1 1 2 2 1 1 1 2 3 3 3 4 4 4 4];
B = sort(A); % Required for the usage of unique below

[~,i1] = unique(B,'first');
[val,i2] = unique(B,'last');
[~,pos] = sort(i2-i1,'descend');
val(pos(1:2))

    1 3

Replace val(pos(1:2)) by val(pos(1:10)) in your case to get the 10 most values. 在您的情况下,用val(pos(1:10))替换val(pos(1:2))以获得10个最大值。 The get the number of elements you can use i1 and i2 . 获取可以使用i1i2的元素数量。

num = i2-i1+1;
num(1:2)

ans =

     7     3

Since you already know how to find the most repeated element, you could use the following algorithm: 由于您已经知道如何找到最重复的元素,因此可以使用以下算法:

  1. Find the most repeated element of the vector 找到向量中最重复的元素
  2. Remove the most repeated element from the vector 从向量中删除最重复的元素
  3. Repeat the process on the new vector to find the 2nd most repeated element 在新向量上重复此过程以找到第二个重复元素
  4. Continue until you have the 10 most repeated elements 继续,直到你有10个最重复的元素

The code would look something like: 代码看起来像:

count = 0;
values = [];
while count < 10
   r = Mode(Vector);
   values = [values r]; % store most repeated values
   Vector = Vector(find(Vector~=r));
   count = count + 1;
end

Not efficient, but it'll get the job done 效率不高,但它会完成工作

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

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