Ramadan FM
Ramadan FM

Reputation: 15

find count of elements in a matrix of two columns

I have a matrix

    1        2
    1        3
    1        4
    2        1
    2        4
    3        1

and I need the resultant matrix contains only

    1        3 (number of elements that related to element 1 (2,3,4))
    2        2 (number of elements that related to element 2 (1,4))
    3        1 (number of elements that related to element 3 (1))

Upvotes: 0

Views: 1158

Answers (4)

magarwal
magarwal

Reputation: 574

use find(a(:,1)==1) to find row numbers with first column value as 1

Upvotes: 0

Amro
Amro

Reputation: 124543

You can use the tabulate function from the Statistics toolbox:

>> tabulate(A(:,1))
  Value    Count   Percent
      1        3     50.00%
      2        2     33.33%
      3        1     16.67%

Another solution using HISTC:

vals = unique(A(:,1));
counts = histc(A(:,1), vals);

The resulting matrix:

>> result = [vals counts]
result =
    1     3
    2     2
    3     1

This is different from ACCUMARRAY/TABULATE in that it does not assume that the elements start at 1. To understand what I mean, modify A as: A(:,1) = A(:,1)+10; before running every solution.

Upvotes: 0

denahiro
denahiro

Reputation: 1199

This is another approach using the array indexing and unique to generate counts:

%demo array
a=[1 1 1 2 2 3]';
%get unique elements
b=unique(a);
%count and put into matrix
result=[b sum((a(:,ones(1,length(b))))'==b(:,ones(1,length(a))),2)];

result =

     1     3
     2     2
     3     1

Upvotes: 0

Andrey Rubshtein
Andrey Rubshtein

Reputation: 20915

The easiest way is to use accumarray :

  accumarray(A(:,1),A(:,2),[],@numel);

Taken from Matlab help:

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.

In our case, we need to group all of the elements and count their number. numel does the counting.


By the way, you don't need the second column of your data at all:

  accumarray(A(:,1),zeros(size(A(:,1))),[],@numel)

Upvotes: 2

Related Questions