Counting the same rows of a 2D matrix

I have a matrix with two columns. I need to make three columns where the third column shows the number of occurrences of the first two as a row in the input matrix.

Basically: Login

[1 1;
 1 1;
 1 2;
 1 2;
 1 3]

      

Desired output:

[1 1 2;
 1 2 2;
 1 3 1]

      

I already know that the right mix of accumulation and uniqueness should make a charm. I just don't know how to combine them correctly.

+3


source to share


2 answers


You are right unique

and are accumarray

perfect for this task:

x = [1 1; 1 1; 1 2; 1 2; 1 3]; % input
[~, v, w] = unique(x, 'rows', 'stable'); % unique indices and labels
c = accumarray(w, 1); % counts
y = [x(v,:) c]; % output

      

Remove the flag 'stable'

if you want the output lines to be sorted in lexicographic order.

You can also replace accumarray

with bsxfun

to get the count:



c = sum(bsxfun(@eq, unique(w), w.'), 2);

      


For the special case where the records x

are positive integers and you want to use them in lexicographic order, you can also use sparse

and find

like this:

x = [1 1; 1 1; 1 2; 1 2; 1 3]; % input
[ii,jj,vv] = find(sparse(x(:,1), x(:,2), 1));
y = [ii(:), jj(:), vv(:)]; % output

      

+3


source


One possible solution:



clear
a=...
[1 1;
 1 1;
 1 2;
 1 2;
 1 3]

[U,~,ic]=unique(a,'rows');
[C] = histc(ic,unique(ic));
Result=[U,C]

      

+3


source







All Articles