Counting the Unique Elements in a MATLAB Array

I was looking for a way to count the number of unique values of an array as part of an assignment. Google turned up with some ideas, but no definite answers. Then I came to know of two functions unique and histc. Here is the code to count the unique elements

a = [1 1 2 3 4 2 4 6]
unique(a)
histc(a, unique(a))

unique produces a nice sorted output of the array with only the unique elements. histc will output an array containing the frequency(number of occurrences) of each element of the array. The output will be :

 unique(a)

ans =

     1     2     3     4     6

histc(a,unique(a))

ans =

     2     2     1     2     1

Oh, and on a sidenote, I came to know of tabulate after all this stuff. Running tabulate(a) will produce:

tabulate(a)
  Value    Count   Percent
      1        2     25.00%
      2        2     25.00%
      3        1     12.50%
      4        2     25.00%
      5        0      0.00%
      6        1     12.50%

So much for the trouble !

Also

Leave a Reply