15

How can I determine the relative frequency of a value in a MATLAB vector?

vector = [ 2 2 2 2 1 1 1 2 2 1 1 1 2 2 2 2 1 2 ];

What function will return the number of occurrences of each unique element?

Ryan Edwards
  • 633
  • 1
  • 10
  • 28
edgarmtze
  • 24,683
  • 80
  • 235
  • 386

4 Answers4

33

You can use unique in combination with histc to get the relative frequency.

A=[1,2,3,1,2,4,2,1]; %#an example vector
unqA=unique(A);

This gives the unique elements as unqA=[1,2,3,4]. To get the number of occurances,

countElA=histc(A,unqA); %# get the count of elements
relFreq=countElA/numel(A);

This gives countElA=[3,3,1,1] and relFreq=[0.3750, 0.3750, 0.1250, 0.1250], which is the relative frequency of the unique elements. This will work for both integers and floating points.

abcd
  • 41,765
  • 7
  • 81
  • 98
10

For the most general case where you have a vector of floating point values, you can use the functions UNIQUE and ACCUMARRAY:

[uniqueValues,~,uniqueIndex] = unique(vector);
frequency = accumarray(uniqueIndex(:),1)./numel(vector);
gnovice
  • 125,304
  • 15
  • 256
  • 359
6

You can use the function tabulate. See this example with your vector.

vector = [ 2 2 2 2 1 1 1 2 2 1 1 1 2 2 2 2 1 2 ];
tabulate(vector);
  Value    Count   Percent
      1        7     38.89%
      2       11     61.11%

If you need it in percent order, do:

t = tabulate(vector);
t = sortrows(t, 3)
Derzu
  • 7,011
  • 3
  • 57
  • 60
0

Referring from this answer:

unqV = unique(vector);
y = zeros(size(unqV));
for i = 1:length(unqV)
    y(i) = sum(unqV(i)==vector);
end

unqV = [1 2]
y = [7 11]

uutsav
  • 389
  • 5
  • 16