Clear Filters
Clear Filters

How to find most frequent value from a Matrix column?

10 views (last 30 days)
We can find one most frequent value from a row or col using the mode function. Anyone please guide me how we can find two or more frequent values from a single row or col. for example A=[ 1; 1; 1; 1; 1; 1; 2; 2; 2; 2; 2; 3; 3; 5; 5; 5; 5; 6; 7; 8;]
In the above example, 1st most frequent value is 1, 2nd most frequent value is 2, and 3rd most frequent value is 5,
So, how we can find the values as 1st most frequent, 2nd, 3rd and so on

Accepted Answer

dpb
dpb on 23 Feb 2017
Edited: dpb on 23 Feb 2017
>> u=unique(A); % find the unique values in vectr
>> [n,b]=histc(A,u); % bin on those and count number in bin
>> [n,is]=sort(n,'descend'); % sort highest first and keep index array of position
>> m=A(arrayfun(@(x) find(b==x,1,'first'),is)); % find the values in original array corresponding
>> [n m] % display the results of number, corresponding value
ans =
6 1
5 2
4 5
2 3
1 6
1 7
1 8
>>
ADDENDUM: To only return N-highest, simply limit the range of the subscripts supplied in arrayfun to only process the number desired instead of entire set.

More Answers (0)

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!