3

So, presume a matrix like so:

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

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

20 0
30 1
40 2

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

Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70
luser
  • 355
  • 4
  • 14

3 Answers3

2

Indeed unique is a good option:

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

Taking apart that last line:

  1. arrayfun(fun,array) applies fun to each element in the array, and puts it in a new array, which it returns.
  2. This function is the function @(y)length(x(x(:,1)==y & x(:,2)==1)) which finds the length of the portion of x where the condition x(:,1)==y & x(:,2)==1) holds (called logical indexing). So for each of the unique elements, it finds the row in X where the first is the unique element, and the second is one.
jpjacobs
  • 9,359
  • 36
  • 45
  • This works perfectly, thank you. Reading the 'help' entry doesn't help me understand how this argument works though; would you be so kind as to explain? – luser Mar 20 '12 at 16:29
1

Consider you have an array of various integers in 'array'

the tabulate function will sort the unique values and count the occurances.

table = tabulate(array)

look for your unique counts in col 2 of table.

mbschenkel
  • 1,865
  • 1
  • 18
  • 40
1

Try this (as specified in this answer):

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

d =
    1
    3

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

>>> res = [c,counts]
Community
  • 1
  • 1
zenpoy
  • 19,490
  • 9
  • 60
  • 87