Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count occurrences on a array using MATLAB [duplicate]

Tags:

arrays

matlab

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

like image 893
user981227 Avatar asked Oct 26 '11 18:10

user981227


2 Answers

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);
like image 152
Jacob Avatar answered Oct 02 '22 02:10

Jacob


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.

like image 20
Doresoom Avatar answered Oct 02 '22 01:10

Doresoom