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
-
Find all unique rows, i.e. unique combinations of both columns. The
unique
function has an option to do thisc = unique( a, 'rows' );
-
Find the unique values in column 1, these are the first column of your ouput
u = unique( c(:,1) );
-
Loop over the unique values in
u
, and check how many rows match in column 1 ofc
(i.e. how many unique combinations use this first value in the inputa
). You can usearrayfun
to do this in a condensed way, or a simple loop would workn = 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];