Thursday, June 20, 2013

Count the frequency of elements in a vector or matrix- part 2

Option 3: accumarray
counts3 = accumarray(M, ones(size(M)), [], @sum);
% or simply: accumarray(M, 1);

This approach is not easy to understand. Let’s see what the function accumarry does first. MATLAB help file states that “accumarray groups elements from a data set and applies a function to each group. A = accumarray(subs,val) creates an array A by accumulating elements of the vector val using the elements of subs as indices. The position of an element in subs determines which value of vals it selects for the accumulated vector; the value of an element in subs determines the position of the accumulated vector in the output”.
So what does it mean exactly? Let’s see an example.
subs = [1; 2; 4; 2; 4];
val = ones(1,5);
A = accumarray(subs, val)

A =

1 % A(1) = val(1) = 101
2 % A(2) = val(2)+val(4) = 1+1 = 2
0 % A(3) = 0
2 % A(4) = val(3)+val(5) = 1+1 = 2
Thus, when we set the input argument “val” as an array of all ones, the function accumarray actually counts the frequency of each element in the first input.
Option 4: sort/diff

[MM idx] = unique( sort(M) );
counts4 = diff([0;idx]);
This approach first finds out the unique element in the input vector, then use “diff” to find out the frequency of each elements. Again, an example is a good way to learn.
M = [1; 2; 4; 2; 4; 5; 2]; % input is a column vector
[MM idx] = unique( sort(M) )
MM =

1
2
4
5

idx =

1
4
6
7

counts4 = diff([0;idx])

counts4 =

1
3
2
1
In the first step of the approach, “unique” is applied on the sorted input. The returned indexes of the unique elements contains the information of the frequency. Then “diff” is used to extract the frequency information. Note that the input is a column vector. If it is a row vector, in the last step, it should be
counts4 = diff([0 idx])


Part 1: http://nw360.blogspot.com.au/2013/06/count-number-of-elements-in-vector-or.html
Part 2: http://nw360.blogspot.com.au/2013/06/count-number-of-elements-in-vector-or_20.html
Part 3: http://nw360.blogspot.com.au/2013/06/count-number-of-elements-in-vector-or_21.html

References:
1 MATLAB help file.
2 http://stackoverflow.com/questions/2880933/how-can-i-count-the-number-of-elements-of-a-given-value-in-a-matrix

1 comment:

1. I am expecting more interesting topics from you. And this was nice content and definitely it will be useful for many people.

Matlab Training in Chennai