Count of values in one column based on another column

I have a table with two columns like so:

1  10 
1  10 
2  30 
2  45 
3  8 
3  8 
....

How can I (in Matlab or Octave) count the number of different values—that is, the number of unique values in the second column for each value in the first column—and show the following?

1 1
2 2
3 1 

You can do this in a few steps

  1. Find all unique rows, i.e. unique combinations of both columns. The unique function has an option to do this

    c = unique( a, 'rows' );
    
  2. Find the unique values in column 1, these are the first column of your ouput

    u = unique( c(:,1) );
    
  3. Loop over the unique values in u, and check how many rows match in column 1 of c (i.e. how many unique combinations use this first value in the input a). You can use arrayfun to do this in a condensed way, or a simple loop would work

    n = arrayfun( @(x) nnz(x==c(:,1)), u );
    

Now you can get the desired output by combining u and n

out = [u, n]; 

This gives the desired result for your example


Here's an approach using unique and accumarray:

x = [1 10; 1 10; 2 30; 2 45; 3 8; 3 8];
[u, ~, w] = unique(x(:,1));
n = accumarray(w, x(:,2), [], @(t) numel(unique(t)));
result = [u n];