Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab - Most repeated values in array (not just mode)

Tags:

arrays

matlab

I have an array with numbers that range from 1 to 4. I need to know which is/are the values that repeat more. In case there's a draw I need to know which are the values so I can make some operations.

Example:

a = [1 1 1 2 2 2 3 4]
Output = [1 2]

a = [1 1 1 2 3 4]
Output = 1

a = [1 2 2 3 3 4 4]
Output = [2 3 4]

Any ideas?

like image 380
user2952272 Avatar asked Dec 02 '22 14:12

user2952272


2 Answers

Alternate vectorised approach using hist and unique

uVal = unique(a);
counts = hist(a,uVal);
out = uVal(counts == max(counts));

Results:

a = [1 1 1 2 2 2 3 4];

>> out

out =

 1     2
like image 158
Santhan Salai Avatar answered Dec 04 '22 04:12

Santhan Salai


The third output of mode gives just that. The input vector doesn't need to be sorted.

[~, ~, v] = mode(a);
result = v{1};
like image 38
Luis Mendo Avatar answered Dec 04 '22 02:12

Luis Mendo