[英]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
. 获取可以使用
i1
和i2
的元素数量。
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: 由于您已经知道如何找到最重复的元素,因此可以使用以下算法:
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.