Reputation: 4139
From 1 dimensional matrix:
list_A = [1,2,4,6,7,7,7,9,10,11,11,11,13,13,13]
How can i get the list of number that have a highest occurrence (in this case occurrence = 3)
The answer that i want should be like this (if we use list_A):
Ans = [7,11,13]
Upvotes: 0
Views: 2528
Reputation: 112659
You can do it most easily with mode
. To get all values you should use the third output, which will be a cell array:
[~, ~, result] = mode(list_A);
result = result{1}.';
EDIT
If your vector is already sorted and you want to exploit that (which mode
apparently doesn't do), you can do it manually with diff
, find
and max
:
ii = find(diff([list_A inf]));
dii = diff(ii);
result = list_A(ii(find(dii==max(dii))+1));
Upvotes: 3
Reputation: 25232
use hist
:
I assumed your vector A
is sorted.
A = [1,2,4,6,7,7,7,9,10,11,11,11,13,13,13];
occ = 3;
out = A( hist(A,A) == occ )
gives:
out =
7 11 13
If A
is not sorted, you could sort it of course, or:
A = [7,7,7,1,2,4,6,9,10,11,11,11,13,13,13]
occ = 3;
out = find( histc(A,1:max(A)) == occ )
If there are also negative numbers:
A = [7,7,7,-4,6,-9,10,-11,-11,-11,13,13,13,-20]
occ = 3;
out = find( histc(A,min(A):max(A)) == occ ) + min(A)-1
or the simple version is working too:
A = sort(A);
out = A( hist(A,A) == occ )
>> out = -11 7 13
Another convenient way is to use the tabulate
function of the Statistics Toolbox, which would even work for decimal values!
A = [7.5,7.5,7.5,-4,6,-9,10,-11,-11,-11,13,13,13,-20]
occ = 3;
T = tabulate(A);
out = T(T(:,2) == occ ,1)
>> out =
-11.0000
7.5000
13.0000
Upvotes: 4