Reputation: 829
I have a matrix like the following:
A =
250 700 950
81 1630 1711
250 700 950
81 1630 1711
250 700 950
81 1630 1711
250 700 950
81 1630 1711
250 700 950
81 1630 1711
250 700 950
81 1630 1711
250 700 950
81 1630 1711
250 700 950
I want to produce a new matrix like this:
B =
81 1630 1711 7
250 700 950 8
containing a row for each unique row in the original matrix, and a fourth column containing the number of times that row appears in the original matrix.
I can use unique(A,'rows')
, but I don't know how to create the
fourth column containing the number of appearances. I know unique has
three possible arguments, and I think that may be the way to do this,
but couldn't figure it out from the documentation.
Upvotes: 2
Views: 216
Reputation: 112659
You can also use sortrows
:
As = sortrows(A);
ind = [ find(any(diff(As).')) size(As,1) ];
B = [ As(ind,:) diff([0 ind]).' ];
Upvotes: 3
Reputation: 30579
You can get the fourth column by manipulating the second and third outputs of unique:
[C,IA,IC] = unique(A,'rows');
counts = sum(bsxfun(@eq,IC,IA.')).';
C = [C counts(IA)]
Or if you also use the 'stable'
option of unique
, then the counts do not need to be reordered (C = [C counts]
).
OR you can use my favorite function, accumarray
:
C = [C accumarray(IC,1)]
Upvotes: 4