Matlab: How to find maximum occurrence in an array if there are more than 1 of the same maximum occurrence

StackOverflow https://stackoverflow.com/questions/22269002

  •  11-06-2023
  •  | 
  •  

Domanda

I am new to Matlab and am finding ways to simplify the following 'problem'.

I want to find the value within an array that has the most occurrence. However at times, my array may contain more than 1 values that share the same maximum occurrence count.

For instance, my equation is...

Array = [ 1 1 2 2 3];
p = mode(Array);

my q will show 1 instead of both 1 and 2.

I know i can calculate the count of individual unique values and compare their number of occurrence. But is there an easier way to do this, since my array can go quite big. Thank you.

È stato utile?

Soluzione

There is an optional output argument to mode that does what you want

[ignore1, ignore2, p] = mode(Array);
p = p{1}; % convert from cell array to vector

p will now contain 1 and 2

Altri suggerimenti

For large arrays, this may be a little faster than using mode:

x = unique(Array);
count = histc(Array,x);
q = x(count==max(count));

Benchmarking:

Array = randi(10,1,1e7);

tic
[~, ~, p] = mode(Array);
p = p{1};
toc

tic
x = unique(Array);
count = histc(Array,x);
q = x(count==max(count));
toc

Results:

Elapsed time is 1.206425 seconds.
Elapsed time is 1.075395 seconds.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top