emma
emma

Reputation: 23

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,

(the elements are from 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.

Upvotes: 2

Views: 279

Answers (3)

Rash
Rash

Reputation: 4336

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)).

I had some doubts so I tested it many times, it seems to work.

Upvotes: 5

Nemesis
Nemesis

Reputation: 2334

You can use unique for that case. In my example, I have 4 numbers and I want to grep the 2 with the most occurances.

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. The get the number of elements you can use i1 and i2.

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

ans =

     7     3

Upvotes: 2

Matt Dalzell
Matt Dalzell

Reputation: 825

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

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

Upvotes: 0

Related Questions