Using SUM and UNIQUE to Count the Values ​​of Values ​​in a Subset of a Matrix

So, suppose such a matrix is:

20 2
20 2
30 2
30 1
40 1
40 1


I want to count the number of times 1 for each unique value of column 1. I could do it the long way [sum (x (1: 2,2) == 1)] for each value, but I think it would be ideal use for UNIQUE functions. How can I fix this to get output like this:

20 0
30 1
40 2


Sorry if the solution seems obvious, my understanding of loops is very poor.


source to share

3 answers

A really unique option is a good option:

res=arrayfun(@(y)length(x(x(:,1)==y & x(:,2)==1)),u)


Separating this last line:

  • arrayfun (fun, array) applies fun to each element of the array and puts it into a new array that it returns.
  • This function is a function @(y)length(x(x(:,1)==y & x(:,2)==1))

    that finds the length of the part of x where a condition is met x(:,1)==y & x(:,2)==1)

    (called boolean indexing). So for each of the unique elements, it finds a string in X, where the first is the unique element and the second is one.


Try this (as pointed out in this answer ):

>>> [c,~,d] = unique(a(a(:,2)==1))
c =

d =

>>> counts = accumarray(d(:),1,[],@sum)
counts =

>>> res = [c,counts]




You have an array of distinct integers in 'array'

the function tabulate

sorts unique values ​​and counts events.

table = tabulate(array)


find your unique account in the col column of table 2.



All Articles