I have a two column matrix. I need to make it three column, where the third column shows the number of appearance of the first two as a row in the input matrix.
Basically: Input
[1 1;
1 1;
1 2;
1 2;
1 3]
Desired output:
[1 1 2;
1 2 2;
1 3 1]
I know already that a proper combination of accumarray and unique should do the charm. I just don't know how to properly combine them.
One possible solution:
You are right,
unique
andaccumarray
are perfectly suited for this task:Remove the
'stable'
flag if you want the ouput rows sorted in lexicographical order.You can also replace
accumarray
bybsxfun
to obtain the counts:For the special case that the entries of
x
are positive integers and you want the ouput in lexicographical order, you can also usesparse
andfind
as follows: