MATLAB: How to calculate number of unique element in array

number of unique elementunique element in array

Hi all.
if I have matrix like:
c =
1 1
1 1
1 1
2 1
2 2
2 3
2 4
2 5
2 5
3 1
3 1
3 2
how can I calculate number of unique element in column 2 according to column 1?
for the above matrix, the result should be:
1 1
2 5
3 2
Thanks in advance

Best Answer

Try splitapply()
c = [
1 1
1 1
1 1
2 1
2 2
2 3
2 4
2 5
2 5
3 1
3 1
3 2]
out = [unique(c(:,1)) ...
splitapply(@(x) numel(unique(x)), c(:,2), c(:,1))]
or accumarray():
out = [unique(c(:,1)) ...
accumarray(c(:,1), c(:,2), [], @(x) numel(unique(x)))];
And if the second column also contain all positive integers in increasing order then you can just try
out = [unique(c(:,1)) ...
splitapply(@max, c(:,2), c(:,1))]
%
out = [unique(c(:,1)) ...
accumarray(c(:,1), c(:,2), [], @max)];