##### 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

##### Option 4: sort/diff

[MM idx] = unique( sort(M) ); counts4 = diff([0;idx]);

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

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

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

ReplyDeleteMatlab Training in Chennai