5

Possible Duplicate:
Determining the number of occurrences of each unique element in a vector

I've the following array:

v = [ 1 5 1 6 7 1 5 5 1 1]

And I need to count the values and show the number that has more appearances.
From the example on the top, the solution would be 1 (there are five 1's)

Thanks in advance

Community
  • 1
  • 1
user981227
  • 155
  • 2
  • 6
  • 12
  • 2
    @Jonas: This might be simpler than that – Jacob Oct 26 '11 at 18:28
  • 1
    other similar questions: [Calculate most common values](http://stackoverflow.com/questions/1846635), [How can I count the number of elements of a given value in a matrix?](http://stackoverflow.com/questions/2880933), [Is there a more elegant replacement for this MATLAB loop?](http://stackoverflow.com/questions/3427291), [function to determine pmf (X) in matlab](http://stackoverflow.com/questions/4068403) – Amro Oct 26 '11 at 20:27

3 Answers3

10

Use mode.

If you need to return the number of elements as well, do the following:

m = mode(v);
n = sum(v==m);
fprintf('%d appears %d times\n',m,n);
Jacob
  • 34,255
  • 14
  • 110
  • 165
9

Another method is using the hist function, if you're dealing with integers.

numbers=unique(v);       %#provides sorted unique list of elements
count=hist(v,numbers);   %#provides a count of each element's occurrence

Just make sure you specify an output value for the hist function, or you'll end up with a bar graph.

Doresoom
  • 7,398
  • 14
  • 47
  • 61
1

@Jacob is right: mode(v) will give you the answer you need.

I just wanted to add a nice way to represent the frequencies of each value:

bar(accumarray(v', 1))

will show a nice bar diagram with the count of each value in v.

Simon
  • 31,675
  • 9
  • 80
  • 92